繁体   English   中英

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

[英]ES6 Javascript: Calling static methods from classes with 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)该方法可以使用“ 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;
  };

}

在这里查看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM