【发布时间】:2018-04-10 02:30:22
【问题描述】:
如何使用类的静态函数访问this 范围?我在这里遗漏了什么吗?
class Example {
constructor() {
this.name = 'Johan';
}
static hello(){
// How to access `this` scope here in the static
Example.name; // Undefined
this.name; // Undefined
}
}
【问题讨论】:
-
thisinhello是类本身 -
这里的前提是有缺陷的——你在一个类的实例中设置
this.name,而静态方法本身就没有。 -
我理解这一点,但使用
Example.name访问this.name会导致未定义。 -
name是一个实例变量。要访问它,您必须创建一个实例(在静态方法中)。Example.name暗示name是类的静态成员,显然不是。 -
你能举个例子吗?
标签: javascript es6-class