Reputation: 2959
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!
Upvotes: 3
Views: 156
Reputation: 103797
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.
Upvotes: 2
Reputation: 74046
In JavaScript a string is a primitive value, which can not be referenced (directly), but is just copied like in your case.
So your friend is right: With the command text: x.text
just the current value of x.text
is copied, which here is `null.
The reassignment of x.text
has no influence on y.text
as this is just a copy and no reference!
Upvotes: 1
Reputation: 943563
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);
Upvotes: 4