簡體   English   中英

如何在JavaScript中使用對象內部的對象屬性

[英]How to use the property of object inside the object in javascript

如何在對象內部使用對象的屬性,如下所示:

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

}

如果您希望對象具有computed屬性,請考慮該屬性,類似於面向對象類中的getter

您可以執行以下操作:

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

以后,您可以訪問obj.c()以獲取所需的值。

您的問題使我開始思考“為什么不使用值和獲取方法創建對象”-這可能對您的要求來說是過大的選擇,但我不得不考慮一下:)

 /* ** 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>"); 

您無法引用尚未創建的對象。

這樣的幫助嗎?

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

這將產生與您期望的上述代碼相同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM