我正在尝试使用node.js,并且我有一组使用module.exports
导出的方法,但是其中一些方法可以在同一对象上重用,但是我不确定该怎么做。在PHP中,我只引用this
。我知道this
可以在原型对象中引用,但是可以在JavaScript对象表示法中做到吗?
示例代码:
module.export = {
foo: (a, b) => {
return a + b;
},
bar: () => {
return foo(2, 5); // This is where i run into problems, using 'this' has no effect.
}
}
答案 0 :(得分:2)
您可以在JavaScript中使用this
关键字。您唯一要做的其他更改是使用实际函数而不是arrow functions,因为箭头函数不会捕获this
的范围。
这里是MDN page on arrow functions的引文。
箭头函数表达式的语法比函数表达式短,并且没有自己的this,arguments,super或new.target。
因为它没有自己的this
,所以在这种情况下不能使用箭头功能。
以下是如何重构代码以按预期方式工作的示例。
module.export = {
foo: function (a, b) {
return a + b;
},
bar: function () {
return this.foo(2, 5);
}
}