Static Members
Adding additional methods directly onto constructors to simulate static members is another common pattern in ECMAScript 5 and earlier. For example:
function PersonType(name) {
this.name = name;
}
// static method
PersonType.create = function(name) {
return new PersonType(name);
};
// instance method
PersonType.prototype.sayName = function() {
console.log(this.name);
};
var person = PersonType.create("Nicholas");
In other programming languages, the factory method called PersonType.create()
would be considered a static method, as it doesn’t depend on an instance of PersonType
for its data. ECMAScript 6 classes simplify the creation of static members by using the formal static
annotation before the method or accessor property name. For instance, here’s the class equivalent of the last example:
class PersonClass {
// equivalent of the PersonType constructor
constructor(name) {
this.name = name;
}
// equivalent of PersonType.prototype.sayName
sayName() {
console.log(this.name);
}
// equivalent of PersonType.create
static create(name) {
return new PersonClass(name);
}
}
let person = PersonClass.create("Nicholas");
The PersonClass
definition has a single static method called create()
. The method syntax is the same used for sayName()
except for the static
keyword. You can use the static
keyword on any method or accessor property definition within a class. The only restriction is that you can’t use static
with the constructor
method definition.
W> Static members are not accessible from instances. You must always access static members from the class directly.