javascript - 引用对象中的其他Key

标签 javascript node.js

我有这个模块:

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/

相关文章:

javascript - 是否可以在javascript中不使用 'this'关键字来获取元素的id

javascript - 如何使用node.js 访问cloudant 文档中的数据?

javascript - 设置 onClick 导致无限循环

javascript - 寻找一种编写自定义 Puppeteer 命令的方法

javascript - 禁用选择输入 Shiny

node.js - 使用 nvm 时 npm install -g

node.js - Sequelize Op.contains 抛出未处理的拒绝错误 : Invalid value

javascript - 在异步 Node 类中处理状态

node.js - 使用 Mocha 运行类似的测试

javascript - 将 css 添加到 jquery 子元素