虽然这是按预期工作的
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();
我收到一个错误
错误TypeError:_this.staticMethod不是函数
箭头函数从外部范围继承它们的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());
当涉及到一般用途时,这是箭头函数的一个怪癖:它们具有this
的通用范围。 (这就是为什么我们必须使用function()
,如果你想要一个更好的调用堆栈)。在第二种方法中,this
指的是调用上下文:window
。
如下面评论中所述,为方便起见,请不要使用简写语法;我们有这么多选择是有原因的。
要修复它,你可以使用function()
来定义第二个函数;对象案例中的()
。
但是,这可行:
class ClassWithStaticMethod2 {
static staticMethod = () => {
return ('staticMethod');
};
static staticMethod2 = function() {
console.log(this)
const yee = this.staticMethod();
return 'staticMethod2 '+yee;
};
}
看看here。