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

标签 javascript reusability object-notation

我正在尝试使用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/

相关文章:

c - 如何使用带 pthreads 的线程池?

ios - 具有循环行为的 iPhone Storyboard

javascript - 如何在创建对象时设置属性的属性

javascript - JSON 和对象文字表示法有什么区别?

ssrs-2008 - 如何在 SSRS 2008 中创建可重复使用的页脚?

javascript - JavaScript 中对象定义末尾的这个方括号后缀是什么意思?

javascript - 如何根据其他JSON数据选择JSON中的数据? Javascript

javascript - Mac 版 Firefox 上的 Audio.js 和 .ogg

javascript - attr() 和 val() 有可用的 += 吗?

javascript - 模块返回空数组