0

This works as intended. Can this be rewritten so that the first SomeClass.prototype.data = data1 is inside the class constructor?

class SomeClass {...}
SomeClass.prototype.data = data1

var instance1 = new SomeClass(...)
console.log(instance1.data) // data1

SomeClass.prototype.data = data2

var instance2 = new SomeClass(...)
console.log(instance1.data, instance2.data) // data2, data2
Shuri2060
  • 729
  • 6
  • 21
  • 1
    Is a class static variable what you want? – Barmar Feb 25 '21 at 20:36
  • Class static can't be accessed by the instances. `this.data` – Shuri2060 Feb 25 '21 at 20:37
  • @Shuri2060 but your `this.data` is also shared between the instances. If you want a one per class declaration thing, `static` is the right choice. – VLAZ Feb 25 '21 at 20:41
  • 1
    Right. The prototype property acts as a default if the instance doesn't have its own property. I just wanted to make sure that's what you want. I don't think class syntax has that. – Barmar Feb 25 '21 at 20:41
  • @Barmar Thanks. Hmm how do I put it - it feels strange to me that you can do this for functions, but not other stuff. – Shuri2060 Feb 25 '21 at 20:49
  • @Shuri2060 *"Class static can't be accessed by the instances."* yes it can: explicitly through the class `SomeClass.data` or through the constructor `this.constructor.data` – Thomas Feb 25 '21 at 20:49
  • Even though the ES6 class syntax is just syntactic sugar for prototypes, it doesn't provide all the capabilities. Prototype properties don't really fit into the traditional class paradigm that ES6 implements. – Barmar Feb 25 '21 at 20:55

0 Answers0