Home > Back-end >  How to set the rvalue of an object item equal to a variable and not just a value?
How to set the rvalue of an object item equal to a variable and not just a value?

Time:11-23

The following prints 3 as expected.

let bar = 3
let obj = { foo: bar }
console.log(obj.foo);

However if I change the value of bar, the value of obj.foo doesn't change. Also if I change the value of obj.foo, the value of bar doesn't change.

This tells me that when the object is created, it didn't really use bar as an rvalue, it used its value as the value. How do I define obj differently so that the two values always match?

CodePudding user response:

Use a getter and a setter

let bar = 3;
let obj = { 
    get foo() { return bar },
    set foo(newValue) { bar = newValue }
};
console.log(obj.foo); // will show current value of 'bar'
obj.foo = 7 // will change 'bar' to 7

See MDN for more info on getters and setters

  • Related