I’m trying to have both the variables “my_a” and letters.a point to the same object.
//i want letters.a to reference (point to) my_a, not be a copy...
//expected output should be: letters.a = c
//made variables into Objects.. but didn't help.
var my_a = new Object('a');
var my_b = new Object('b');
var letters = {'a': my_a, 'b': my_b};
$('#output').append('my_a = ' + my_a + '<br>');
$('#output').append('leters.a = ' + letters.a + '<br>');
my_a = new Object('c');
$('#output').append('my_a = ' + my_a + '<br>');
$('#output').append('letters.a = <span style="color:red">' + letters.a + '</span>');
See this fiddle:
But as you can see by the output, this is not working.
Any ideas? Is this possible with javascript?
Thank you.
The answer to your question is “yes”, but I think that your question doesn’t describe accurately the thing you’re trying to do. What you’d like is for
letters.ato be reference to the variable “my_a”, in the sense of what one can do in C++ with the&operator. That’s not possible in JavaScript.At the statement:
you’re giving “my_a” a new, different value. Thus,
letters.astill refers to the same thing it did, while “my_a” has changed. There’s no way to make a variable or object property “track” another (in JavaScript).edit — actually it occurs to me that you could do something like what you’re looking for by defining a “getter” for the “a” property of “letters”, one that returns the current value of “my_a”. It’d require that feature in the JavaScript engine you’re using, but it’d look something like:
IE before IE9 doesn’t support that unfortunately. Here’s the updated jsfiddle.