如何在javascript中使用对象内部的对象属性

时间:2018-05-14 00:42:04

标签: javascript

如何在对象内使用对象的属性,如下所示:

var obj = {
  a: 1
  b: this.obj + this.obj.a

}

3 个答案:

答案 0 :(得分:1)

如果您希望对象具有computed属性,请将其视为与面向对象类中的getter类似。

您可以执行以下操作:

var obj = {
  a: 1,
  b: 2, 
  c: () => this.a + this.b
}

稍后,您可以访问obj.c()以获得所需的值。

答案 1 :(得分:0)

你的问题让我想到“为什么不用价值观和吸气剂创造一个对象” - 这可能对你的要求有点过分,但我不得不考虑这个:)

/*
** This function creates an object by rewriting the values of the first 
** object as "value properties" (meaning the values stay as they are but 
** can be accessed and modified like properties), while the second object 
** expects functions that act as getters, which can access the values 
** defined in the first object as well the getters from itself.
*/
const LetsBeLazy = function(values, lazy) {
  for(let key in values) {
    Object.defineProperty(this, key, {
      value: values[key],
      configurable: true,
      writable: true
    });
  }
  for(key in lazy) {
    Object.defineProperty(this, key, {
      get: lazy[key]
    });
  }
  return this;
}

// Pointless example to get the point through :)
var obj = LetsBeLazy({
  // These values stay as they are and can be 
  // accessed and changed from outside with the property notation
  firstName: 'John',
  lastName: 'Doe',
  salutation: 'Mr.',
  buildFullName: (random) => `${salutation} ${firstName} ${lastName} (${random})`
}, {
  // These functions are lazily evaluated and can access other getters
  // as well the values from the previous object - notice that since
  // they are properties, they can't be called like functions.
  sayHello: () => `Hello ${buildFullName(Math.ceil(Math.random() * 10))}`,
  sayHelloWithABang: () => `${sayHello}!`
});

document.write(obj.sayHello + "<br>");

obj.firstName = 'Jane';
obj.salutation = 'Mrs.';
document.write(obj.sayHelloWithABang + "<br>");

document.write(obj.buildFullName('X') + "<br>");

答案 2 :(得分:0)

您无法引用尚未创建的对象。

这样的事情有帮助吗?

var obj = {
  a: 1
}
obj.b = obj + obj.a

这将得到与上述代码相同的结果。