【发布时间】:2019-02-15 13:38:45
【问题描述】:
虽然这按预期工作
class ClassWithStaticMethod {
static staticMethod() {
return ('staticMethod');
};
static staticMethod2() {
const yee = this.staticMethod();
return 'staticMethod2 '+yee;
};
}
console.log(ClassWithStaticMethod.staticMethod2());
//staticMethod2 staticMethod
这是,
i) 可以使用类名访问 staticMethod(),并且
ii) 此方法可以通过使用“this”调用同一类中的另一个静态方法,
这行不通
class ClassWithStaticMethod {
static staticMethod = () => {
return ('staticMethod');
};
static staticMethod2 = () => {
const yee = this.staticMethod;
return 'staticMethod2 '+yee;
};
}
console.log(ClassWithStaticMethod.staticMethod2());
//staticMethod2 undefined
从某种意义上说,我仍然可以访问 staticMethod() 方法,但我无法访问第一个方法中的另一个方法。我不确定,如果我使用
const yee = this.staticMethod();
我收到一个错误
错误类型错误:_this.staticMethod 不是函数
【问题讨论】:
-
这是箭头函数的一个问题:它们具有
this的通用范围。 (这就是为什么我们必须使用function()如果你想要一个更好的调用堆栈)。在第二种方法中,this指的是调用上下文:window。 -
@weirdpanda - 这不是箭头函数的问题。这就是它们的设计方式和目的!如果您想要
this的常规方法调用行为,请使用常规方法调用,而不是箭头调用。 -
@jfriend00,很抱歉,我的语言有点不对劲。
标签: javascript ecmascript-6 es6-class arrow-functions