简体   繁体   中英

How to use the property of object inside the object in javascript

How to use the property of object inside the object, like this:

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

}

If you want to have computed property with your object, think about it similar to a getter in object-oriented class.

You can do something like:

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

Later, you can access obj.c() to get the desired value.

Your question got me thinking about "Why not creating an object out of values and getters" - it is probably an overkill for your requirements, but i had to think this out :)

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

You can't reference an object that hasn't been created yet.

Would something like this help?

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

This will give the same result as you seem to expect from the code above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM