Skip to content
Advertisement

How to set a variable on prototype in ES6 Classes?

class SomeClass {

  someMethod() {
    // some code
  }

  someMoreMethod() {
    // some more code
  }

}

var someInstance = new someClass();

We know that in the code above, methods someMethod and someMoreMethod would get attached to the prototype of someInstance object. But, what if we want to attach some property (not method) to the prototype. I tried doing the following but it throws error:

class SomeClass {

    someProperty = "Some Value";

    someMethod() {
      // some code
    }

    someMoreMethod() {
      // some more code
    }

 }

Advertisement

Answer

ES6 classes do not currently support fields. However, you can add properties to the prototype directly:

SomeClass.prototype.someProperty = "Some Value";
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement