I was reading up on ES6 classes, and it is said to be just syntactic sugar. Then why does calling Object.keys on Class.prototype not list the methods of the class?
class Class { whoami() { return "class"; } }
function Proto() {}
Proto.prototype.whoami = function () { return "proto"; }
console.log(Class.prototype); // { constructor: f() {}, whoami: f() {} }
console.log(Proto.prototype); // { constructor: f() {}, whoami: f() {} }
console.log(Object.keys(Class.prototype)); // [] <--- WHY ???
console.log(Object.keys(Proto.prototype)); // ["whoami"]
The difference you're observing between
Object.keys(Class.prototype)andObject.keys(Proto.prototype)has to do with how class methods are defined and stored in ES6 classes compared to traditional prototype-based objects.In your example,
Classis an ES6 class, and Proto is a traditional constructor function with a manually defined prototype.When you define a method in an ES6 class using the shorthand syntax, like
whoami() { return "class"; }, the method is added to the class prototype. However, these methods are not enumerable by default, which means they won't show up when you iterate over the object's properties usingObject.keys().This is a design choice made to mimic the behavior of class methods in other programming languages like Java. In most cases, you don't want these internal methods to be visible when iterating through an object's keys.
If you want to make the methods enumerable (and thus appear in
Object.keys(Class.prototype)), you can explicitly set the method's propertydescriptorto be enumerableWhen you manually define a method on the prototype of a constructor function like
Proto.prototype.whoami = function () { return "proto"; }, the method is added to the prototype with theenumerableproperty set to true by default. This is why you see the method inObject.keys(Proto.prototype).