我有这个模块:
exports.yeah = {
hallo: {
shine: "was",
yum: this.hallo.shine
}
}
如您所见,我尝试在yum: this.hallo.shine
中引用shine
但是当我尝试执行我的脚本时,我收到此错误:
TypeError: Cannot read property 'shine' of undefined
范围好像不对!
我尝试了不同的东西,例如 module.exports.yeah.hallo.shine
但这根本行不通!我该如何修复这个错误? 谢谢
最佳答案
您可以使用 javascript getters
var exports = {};
exports.yeah = {
hallo: {
shine: "was",
get yum() {
return this.shine
}
}
};
document.write(exports.yeah.hallo.yum);
注意,getter
上下文中的 this
将引用 hallo
而不是 yeah
根据文档
The get syntax binds an object property to a function that will be called when that property is looked up.
因此,由于在对象初始化之后调用了 getter 函数(查找),this
可用于引用 shine
更新
Lets say the object is build like that {hallo1: {..}, hallo2: {..} } . And now I want to reference in hallo1.yum = hallo2.shine Is that possible?
是的,这是可能的,因为在获取时对象已初始化,您可以引用对象本身而不是this
var exports = {};
exports.yeah = {
hallo1: {
shine: "was",
get yum() {
return exports.yeah.hallo2.yum;
}
},
hallo2: {
shine: "is",
get yum() {
return this.shine;
}
}
};
document.write(exports.yeah.hallo1.yum);
关于javascript - 引用对象中的其他Key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30765608/