0

With ECMAScript 5, one could do the following to share a property between all objects of a class, accessible through each object same way as if it were a property defined on each such object:

function Message {
}

Message.prototype.importance = "normal";

Evaluating (new Message()).importance would yield the value "normal", but the essential thing here is that importance is the property of the prototype object, so no matter how many message objects one creates, given how they all share the same prototype, the property and thus its value are shared.

I can't seem to find out how I can define a property like that with an ES6 class. From what I understand, ES6 classes still use prototype based inheritance, although I am also aware that the standard describes a class as a distinct first-class citizen.

Assume I define the class as follows:

class Message {
}

Is there any new (ES6) syntax that allows me to define the aforementioned property. I know I can add Message.prototype.importance = "normal" below the class definition, but I am curious if there is any ES6-specific syntax for this?

Armen Michaeli
  • 8,625
  • 8
  • 58
  • 95
  • 1
    No, there is no ES6 syntax for this - data properties on the prototype are just too uncommon, as data usually would not be shared. (Why not make it a static property if it's a constant?). The closest you'd get would be `get importance() { return "normal"; }` – Bergi Oct 05 '18 at 14:24
  • Getters are not the same thing and neither are static properties. Thanks for the clarification, regardless. – Armen Michaeli Oct 05 '18 at 15:16
  • Yeah this pattern is just not recommended. If the property needs a default value, you can always assign it in the `Message` constructor. – loganfsmyth Oct 05 '18 at 16:22
  • 1
    In ES2022 you can use a [static block](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_static_initialization_blocks) and write this inside it: `this.prototype.importance = "normal"`. It's not really any more elegant but at least it keeps everything encapsulated in the class definition. – Inkling Apr 05 '22 at 05:54

0 Answers0