Reputation: 4113
I don't know really what to call this idea, but I want to point an object's key to a variable's value. When I do that, though, the object's key value is pointed to a copy of the original value, rather than the original variable itself.
let someArr = ['the original array', 1];
const someObj = {
theArr: someArr
}
console.log(someObj.theArr)
// ['the original array', 1]
someArr = ['a new array', 2]
console.log(someObj.theArr)
// ['the original array', 1]
So what's happening here is that when the obj is created and the key value is set to someArr
the value of someArr
is being copied to the key, but the actual someArr
array object is not being pointed to.
First, why is this? What is this called? Second, how could I make someObj.theArr
always stay equal to the value of someArr
?
Upvotes: 0
Views: 48
Reputation: 14165
So what's happening here...why is this?
As zerkms states, there is no way to maintain a reference to an externally scoped variable upon creation of the object literal in JavaScript. When JavaScript creates an object, it gets the value of the variable you've assigned and creates an internal copy of that value.
What is this called?
In other languages like C
and its derivatives, indirectly in Java and some others, this would be called a pointer assignment (see #3). That is not available in JavaScript.
how could I make
someObj.theArr
always stay equal to the value ofsomeArr
The code below uses set
and get
from the Class syntax to accomplish your goal. This is one of a few ways to do this. But, this is not recommended as it is a poor design. It is never a good idea to disassociate a property and its actual value.
let someArr = ['the original array', 1];
class SomeObj {
get theArr() {
return someArr;
}
set theArr(arr) {
theArr = arr;
someArr = arr;
}
}
const someObj = new SomeObj();
console.log(someObj.theArr)
someArr = ['a new array', 2]
console.log(someObj.theArr)
Upvotes: 3