【问题标题】:es6 variable with functions and using "this" [duplicate]带有函数并使用“this”的es6变量[重复]
【发布时间】:2021-06-05 18:14:10
【问题描述】:

我现在正在学习 ES6。只是想通了一点关于类。 现在,我在 JSON 对象中有一组助手。我如何引用它自己?我使用 babel 将其转换为 ES5,它不喜欢它,它使“_this”脱离“this”。

const pixieLib = {
  methodA : (arg1) => {
    console.log('foo');
  },

  methodB : () => {
    this.methodA();
  }
};

如果有更好的方法来制作助手,欢迎所有建议,只要他们与 Babel 玩得很好。

【问题讨论】:

  • 我不明白这与classes 有什么关系。另外我认为您的问题与 Babel 无关,即使在本机执行时,代码也不起作用。

标签: ecmascript-6 babeljs


【解决方案1】:

您使用了一个箭头函数,根据定义,它在创建它的地方关闭。

如果你不使用,它会正常工作:

const pixieLib = {
  methodA : function(arg1) {
    console.log('foo');
  },

  methodB : function()  {
    this.methodA();
  }
};

Babel REPL test

编辑:

或使用@trincot 指出的 ES6 方法定义语法。

const pixieLib = {
  methodA(arg1) {
    console.log('foo');
  },

  methodB()  {
    this.methodA();
  }
};

REPL Result

【讨论】:

  • @trincot 你是对的,我会编辑。
猜你喜欢
  • 2018-08-01
  • 2018-07-10
  • 2019-03-30
  • 2016-01-08
  • 2016-07-04
  • 2020-02-21
  • 2017-04-26
相关资源
最近更新 更多