Class(类)的方法都会被实例继承,但是对于在方法名前面加了static关键字的方法,则不能直接被实例继承,只能通过类来调用,称之为“静态方法”。
class Person {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(`This is ${this.name}`);
}
static create(name) {
return new Person(name);
}
}
const p1 = new Person('Tom');
p1.sayHi(); // This is Tom
// create为静态方法没有被实例对象p1继承
p1.create(); // TypeError: p1.create is not a function
// 只能通过类来调用
const p = Person.create('Jack');
p.sayHi(); // This is Jack