javascript - ES6 Javascript : Calling static methods from classes with arrow functions

标签 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) 这个方法可以通过使用“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/

相关文章:

javascript - 为什么在 super() 之前不允许这样做

Javascript:如何编写接受不同数量参数的函数

windows-7 - 如何在Windows操作系统中安装Babel?

javascript - 如何在 javascript CLASSES (ES6) 上实现静态成员(非函数)

javascript - 如何在 ES6 中实现命名构造函数

javascript - 无法移动使用 super 的方法

javascript - 日期时间选择器。不显示任何计时器

javascript - 从页面列表中查找单词

javascript - 尝试滚动时如何修复闪烁效果

javascript - .map() 一个 Javascript ES6 map ?