我正在尝试使用node.js,并且我有一组使用module.exports
导出的方法,但是其中一些方法可以与同一对象重用,但我不确定怎么办呢?在 PHP 中,我将简单地引用 this
。我知道 this
可以在原型(prototype)对象中引用,但同样可以在 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.
}
}
最佳答案
您可以使用this
JavaScript 中的关键字。您必须进行的唯一其他更改是使用实际函数而不是 arrow functions ,因为箭头函数不捕获 this
范围。
这里引用 MDN page on arrow functions .
An arrow function expression has a shorter syntax than a function expression and does not have its own this, arguments, super, or new.target.
因为它没有自己的 this
在这种情况下你不能使用箭头函数。
下面是一个示例,说明如何重构代码以按照您期望的方式工作。
module.export = {
foo: function (a, b) {
return a + b;
},
bar: function () {
return this.foo(2, 5);
}
}
关于JavaScript 对象表示法 - 在同一对象内使用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51408532/