为什么没有输出2
class People {
static homeland = 1;
test() {
this.homeland += 1
console.log(this.homeland);
}
}
let a = new People()
a.test()
为什么没有输出2
class People {
static homeland = 1;
test() {
this.homeland += 1
console.log(this.homeland);
}
}
let a = new People()
a.test()
你好,在 ES6 Class 语法中通过 static
声明的是静态方法或属性,其不能在类的实例上调用,而只能通过类本身调用。上例中你只能通过 People.homeland
获取 static homeland
的值。(关于 Class static 方法的具体用法,你可以参考 MDN文档 Class static。)
如果你想声明实例上的属性,直接声明在 Class 内部即可:
class People {
homeland = 1
test() {
this.homeland += 1;
console.log(this.homeland);
}
}
let a = new People();
a.test(); // 2
希望这个回答能够对你有所帮助!
10 回答11.7k 阅读
2 回答3.2k 阅读✓ 已解决
4 回答2.2k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
3 回答840 阅读✓ 已解决
3 回答1k 阅读✓ 已解决
2 回答1.2k 阅读✓ 已解决
People.homeland // 类上才有 homeland
new People().homelnad // undefined // 实例没有 homeland
undefined + 1 // NaN
不知道你想怎么用