PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 4, 2022

[FIXED] How to set the rvalue of an object item equal to a variable and not just a value?

 July 04, 2022     javascript, object, pass-by-reference     No comments   

Issue

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?


Solution

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



Answered By - skara9
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing