ES6 Javascript:使用箭头函数从类中调用静态方法

时间:2018-09-11 05:40:07

标签: javascript ecmascript-6 es6-class arrow-functions

虽然这可以按预期工作

class ClassWithStaticMethod {

  static staticMethod() {
    return ('staticMethod');
  };

  static staticMethod2() {
    const yee = this.staticMethod();
    return 'staticMethod2 '+yee;
  };

}

console.log(ClassWithStaticMethod.staticMethod2());
//staticMethod2 staticMethod

这是

i)可以使用类名访问staticMethod(),并且

ii)此方法可以使用“ ”来调用同一类中的另一个静态方法,

这不起作用

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不是函数

2 个答案:

答案 0 :(得分:2)

箭头函数从外部作用域继承其this而不是其this,具体取决于它们的调用上下文。由于staticMethod2尝试访问this.staticMethod,因此只有在this引用ClassWithStaticMethod的情况下,即staticMethod2标准函数< / em>,而不是箭头功能。

您还需要调用 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());

答案 1 :(得分:2)

在通用方面,这是一个带有箭头功能的怪癖:它们具有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