Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript referenced value not updated?

I basically have an object, but this object will only be filled after user input. But the other classes are using this object also. But then after I fill the object with the real object, it doesn't get updated in the other classes.

Example :

var x = {
  text: null
}
var y = {
  text: x.text
}

x.text = 'trlalala';

console.log(y.text);
console.log(x.text);

but when I run it, y.text will print out null. But the value should be updated already. One of my friend told me it's because y.text copy the structure of x.text instead of the reference. Been stuck for a while. :\

Any input will be appreciated, thanks!

like image 942
Rowanto Avatar asked Dec 10 '25 14:12

Rowanto


2 Answers

text: x.text looks at the value of x.text (a reference to null) and sets y.text to that.

When you say x.text = 'trlalala', then you change the value of x.text (so it is a reference to the immutable string 'trlalala') but the value of y.text remains a reference to null.

You would need an intermediate object that you get a reference to if you want to share data like that. (Since then you would be dealing with a reference to an object)

var x = {
  data: { text: null }
};
var y = {
  data: x.data
};

x.data.text = 'trlalala';

console.log(y.data.text);
console.log(x.data.text);
like image 132
Quentin Avatar answered Dec 13 '25 02:12

Quentin


When you define y, you're defining a property (i.e. a constant value) rather than a method. And you define the value of text to be x.text - which means at definition time, the value of x.text is looked up and used as the (constant) value of y.text.

If you want changes in x.text to be reflected in y, then you can define y.text to be a function, so that this value is looked up on-demand every time that the method is called. This might look something like this:

var y = {
   text: function() {
      return x.text;
   }
};

Now whenever you update x.text, subsequent calls to y.text() will yield the new value.

like image 25
Andrzej Doyle Avatar answered Dec 13 '25 03:12

Andrzej Doyle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!