1
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
    }

 }
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
  • Possible duplicate of [ES6 class variable alternatives](https://stackoverflow.com/questions/22528967/es6-class-variable-alternatives) – Joseph Webber Aug 20 '18 at 16:53
  • 1
    "*set a variable on prototype*" - you can create a property, but you better make it constant not variable as you probably don't want globally shared state amongst your instances. Of course, a constant could also be placed anywhere else. – Bergi Aug 20 '18 at 18:19

2 Answers2

10

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

SomeClass.prototype.someProperty = "Some Value";
SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
0

There is no syntax for defining non-function prototype fields, so they need to be added manually:

SomeClass.prototype.someProperty = "Some Value"

// a nicer way to define multiple at once:
Object.assign(SomeClass.prototype, {
   someProperty: "Some Value",
   anotherProperty: "Another Value",
})

Anonymous Classes

If you need to define an "anonymous" class (e.g. within an expression, without defining a variable), you can use a helper function, such as:

function def_proto(cls, proto) {
    Object.assign(cls.prototype, proto)
    return cls
}

console.log(
    def_proto(class {
        someMethod() {
            return this.someProperty
        }
    }, {
        someProperty: "Some Value",
    })
)

Static Initialization Blocks

This feature is not widely supported yet. But in the future, the previous example can be written as:

console.log(
    class {
        someMethod() {
            return this.someProperty
        }
        static {
            // Note: in static methods, `this` refers to the CLASS
            this.prototype.someProperty = "Some Value"
        }
    }
)
12Me21
  • 992
  • 10
  • 22