JavaScript 对象表示法 - 在同一对象内使用方法?

JavaScript Object notation - using methods inside the same object?

我正在尝试使用 node.js 并且我有一组方法正在使用 module.exports 导出,但是有些方法可以重复用于同一对象,但我不确定如何去做这件事。在 PHP 中,我将简单地引用 this。我知道 this 可以在原型对象中引用,但是在 JavaScript Object Notation 中也可以这样做吗?

示例代码:

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 keyword in JavaScript. The only other change you will have to make is use actual functions instead of 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);
    }

}