从严格导出默认模块中的另一个本地方法中调用本地 fooBar 方法时获取“_this.fooBar 不是函数”

Getting "_this.fooBar is not a function" when calling local fooBar method from within another local method inside strict export default module

这是 StackBlitz 示例代码:js-m8uxyl

这是我遇到问题的粘贴模块:

'use strict'

export default {
  isTrue: (val) => {
    return val ? true : false;
  },

  doSquare: (val) => {
    return this.isTrue(val) ? val * val : false;
  },

  doCube: (val) => {
    return this.doSquare(val) * val;
  }
}

如您所见,当我尝试 运行 doSquaredoCube 方法时,出现以下错误:_this.isTrue is not a function_this.doSquare is not a function.

如何从其他本地方法中正确调用本地方法? 此刻我真的很困惑...

这是由箭头函数中模块和 this 的工作方式共同造成的。

首先,该文件是一个 ES6 模块,这使得脚本顶层的 this 成为模块定义对象。

其次,箭头函数 (()=>{}) 从它们声明的范围继承 this,不像旧样式 function(){},其中 this 将是它被声明为 属性 的对象。这意味着函数内部的 this 是顶级模块对象,而不是导出对象。

如果它们是使用旧式 function(){} 声明的,它们应该会按预期工作。