GWo*_*ing 5 javascript ecmascript-6 arrow-functions es6-class
虽然这按预期工作
class ClassWithStaticMethod {
static staticMethod() {
return ('staticMethod');
};
static staticMethod2() {
const yee = this.staticMethod();
return 'staticMethod2 '+yee;
};
}
console.log(ClassWithStaticMethod.staticMethod2());
//staticMethod2 staticMethod
Run Code Online (Sandbox Code Playgroud)
这是,
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
Run Code Online (Sandbox Code Playgroud)
从某种意义上说,我仍然可以访问 staticMethod() 方法,但我无法访问第一个方法中的其他方法。我得到未定义,如果我使用
const yee = this.staticMethod();
Run Code Online (Sandbox Code Playgroud)
我收到一个错误
错误类型错误:_this.staticMethod 不是函数
箭头函数this从外部作用域继承它们,而不是this取决于它们的调用上下文。由于staticMethod2尝试访问this.staticMethod,因此只有在this引用时才有效ClassWithStaticMethod- 也就是说, ifstaticMethod2是标准函数,而不是箭头函数。
您还需要调用 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());Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3652 次 |
| 最近记录: |