Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Object.keys(Class.prototype) is not same as Object.keys(Proto.prototype). Why?

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"]

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The difference you’re observing between Object.keys(Class.prototype) and Object.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, Class is 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 using Object.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 property descriptor to be enumerable

When 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 the enumerable property set to true by default. This is why you see the method in Object.keys(Proto.prototype).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading