虽然这按预期工作
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();
我得到一个错误
error TypeError: _this.staticMethod is not a function
最佳答案
箭头函数从外部范围继承它们的 this
而不是它们的 this
取决于它们的调用上下文。由于 staticMethod2
尝试访问 this.staticMethod
,因此仅当 this
引用 ClassWithStaticMethod
时才有效 - 也就是说,如果 staticMethod2
是一个标准函数,而不是箭头函数。
您还需要调用 this.staticMethod()
。 (const yee = this.staticMethod;
将导致 staticMethod
被强制转换为字符串,而不是被调用)
改变这两个问题,它按预期工作:
class ClassWithStaticMethod {
static staticMethod = () => {
return ('staticMethod');
};
static staticMethod2 = function() {
const yee = this.staticMethod();
return 'staticMethod2 '+yee;
};
}
console.log(ClassWithStaticMethod.staticMethod2());
关于javascript - ES6 Javascript : Calling static methods from classes with arrow functions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52269317/