What does 'static' mean in this ES6 example?

Viewed 165

This example is from the docs for Stimulusjs. I've been able to find documentation on ES6 static methods, but this does not look like a method. Or is this some kind of shorthand? Why is there a 'static' key word for a variable?

export default class extends Controller {
  static targets = [ "name" ]

  greet() {
    const element = this.nameTarget
    const name = element.value
    console.log(`Hello, ${name}!`)
  }
}
1 Answers

That syntax is allowed when using babel's transform-class-properties plugin. The equivalent in plain javascript would be:

class MyClass extends Controller {
  greet() {
    const element = this.nameTarget
    const name = element.value
    console.log(`Hello, ${name}!`)
  }
}

MyClass.targets = ["name"];

export default MyClass

EDIT: pre ES6, this would be done as:

var MyClass = function () {
  Controller.call(this);
};
MyClass.prototype = Object.create(Controller.prototype);
MyClass.prototype.greet = function () {
    var element = this.nameTarget
    var name = element.value
    console.log('Hello, ' + name + '!');
}
MyClass.targets = ["name"];
Related