【发布时间】:2021-11-08 06:41:19
【问题描述】:
您好,我是 JavaScript 新手。我想知道类构造函数是否是一个特殊的类静态方法。我有这样一个例子:
class warrior {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get fullName() {
return `${this.firstName} ${this.lastName}`;
}
sayHello() {
return `Hello my name is ${this.fullName}`;
}
static createWarrior(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
return this;
}
}
let warrior1 = new warrior("Ashley", "Yuna", 25);
warrior1.sayHello();
let warrior2 = warrior.createWarrior("Kris", "Snow", 23);
warrior2.sayHello();
如果类构造函数是一种静态方法,如何修改createWarrior静态方法才能返回战士实例?
【问题讨论】:
-
可能与您问题的核心无关,但您能否详细说明为什么使用标准
constructor不符合您的要求? -
我没有看到任何真正的用例,但我只是好奇是否有可能?
-
在
static方法中,this指的是类本身,而不是实例。见How does the “this” keyword work?。为什么不static createWarrior(...args){ return new this(...args); }?
标签: javascript