In many other programming languages, one can get the value of a variable either as a copy or by reference.
Example (PHP):
$value = 'a value';
$copy = $value;
$ref = &$value;
$value = 'new value';
echo $copy; // 'a value'
echo $ref; // 'new value'
Is there a similar feature in JavaScript? Can I reference i.e. an object's property and even if I replace the property with a new string/object, the referring variable will point to the new data?
Here is an example code of what I am trying to achieve:
var obj = { property: 'a value' }
var another = obj.property // save this by reference to this variable
obj.property = 'new value'
console.log(another) // expected: 'new value'
So far I have tried using getters/setters, but this does not help since when I assign the property to a new variable, the getter is called and returns the actual value. I am quite sure this would be easy to implement using Node.js EventEmitter or by using function calls instead of properties, but I am really looking for some kind of language feature that I might have missed or for some obvious, easy way of doing these things.
Thanks!
In Javascript, objects are passed by refernce but primitives (strings, numbers and booleans) by value:
var obj = { property: 'a value' };
var another = obj.property; // value
obj.property = 'new value';
console.log(another); // gives a value
But
var obj = { property: 'a value' };
var another = obj; // reference
obj.property = 'new value';
console.log(another.property); // gives new value