我很好奇如何访问 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/