A few weeks ago, I wrote a post about using the new class syntax in JavaScript. As I explained there, the new class syntax, introduced in ECMAScript 2015 (ES6), is just a syntactical sugar for the extant prototypical inheritance in JavaScript. The new syntax, together with the extends keyword, has obvious advantages, which make the code easier to write and understand.
However, one disadvantage of the new approach is that it does not allow you to define "prototype properties," i.e. properties that reside on the prototype object, not on the class instances. In fact, it does allow you to define accessor properties, but defining data properties on the prototype is not possible in the new class syntax. The usual approach is to instantiate an object in the class constructor with the required properties. Still, there may be cases that you want a property to reside on the prototype object. These are different from static properties that reside on the constructor function itself, because those properties are not subject to inheritance and are not modifiable on instance objects.
I guess there is a rationale for this decision, but I don't know what is. The following code snippet shows an accessor property, which is defined on the property object. As I said, you cannot define a data property with this syntax.
class Test {
constructor() {}
get name() {
return "Ali";
}
}
var a = new Test();
console.log(a.name); // Ali
console.log(a.hasOwnProperty("name")); // false
console.log(a.constructor.prototype.hasOwnProperty("name")); // true
Maybe I have missed something. I know that the properties could be instantiated on the instance object, but I鈥檇 like to know why it is not possible to define prototype "data" properties with the new class syntax.