javascript - 如何访问 module.exports 中的对象属性

标签 javascript object express javascript-objects

我很好奇如何访问 module.exports 中的另一个对象属性。

情况是这样的:

module.exports = {

    text: 'abcd',
    index: (req, res)=>{
    console.log(text) <-- is not defined
    console.log(this.text) <-- undefined
    }
}

well then, how to access the text property? thanks guys need your explanation.

最佳答案

Javascript 没有内置的方法来引用同一对象中的其他属性。有充分的理由说明为什么它不能对任何任意属性执行此操作。因此,您要么必须确保 this 中有正确的对象值,要么您需要自己将适当的对象引用保存在您可以访问的地方。

这是一种您自己保存对象引用的方法,它适用于单例对象:

let myObj = {

 text: 'abcd',
 index: (req, res)=>{
   console.log(myObj.text)
 }

}

module.exports = myObj;

如果您知道 .index() 将始终作为您的 module.exports 上的一个方法被适本地调用(这是通常的情况),那么您可以停止使用 => 定义并使用普通的 function 定义(它应该几乎总是用于方法声明)然后 this 将有所需的值。

module.exports = {

 text: 'abcd',
 index: function(req, res) {
   console.log(this.text)
 }
}

只要像这样调用 .index() 索引,这就会起作用:

let myModule = require('myModule');
myModule.index(req, res);

人们往往会爱上箭头语法,而忘记它几乎不应该用于方法定义,因为它不会将 this 设置为宿主对象,这会给方法带来问题。相反,使用对象方法的常规 function 定义。


箭头函数通常对回调函数非常有用,您希望回调函数能够访问您环境中的 this 值(称为 this 的词法值)。以下是一些有用的示例:

class Timer {
    delay(t, cb) {
       this.timer = setTimeout(() => {
           // preserve this value inside a callback
           this.timer = null;
           cb();
       })
    }
}

或者

// preserve this value inside a callback
let filtered = myArray.filter(item => {
    return item.id !== this.master.id;
});

另一方面,您几乎不想对方法使用箭头声明,因为这会覆盖 this 的常用对象值,并将其替换为 this 的词法值

关于javascript - 如何访问 module.exports 中的对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41647108/

相关文章:

javascript - 在 Node JS 中使用 YQL

javascript - 如何在单击单选按钮之一时启用文本框

java - 按名称排序 Object[][] Java

node.js - Express JS 4.0 命令行工具不工作

node.js - `express` 应用程序 - 无法使用 `post` 测试 `postman` 请求

javascript - AngularJS 强制提交不发送一些隐藏的输入值

javascript - 在 Javascript 中翻译 Bro_Log 时间戳

JavaScript,具有图像键值的对象

arrays - 比较两个对象列表A和B的列表,并存储在 Dart 中的另一个列表C中

database - Node.js 在 app.js 中导出模块与在单个模块中包含 app.js