是否有可能有 2 个变量指向同一个对象?(javascript) [英] Is it possible to have 2 variables pointing to the same object? (javascript)
问题描述
我试图让变量my_a"和letters.a指向同一个对象.
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>');
看到这个小提琴:
但是正如您在输出中看到的那样,这是行不通的.
But as you can see by the output, this is not working.
有什么想法吗?这可以用 JavaScript 实现吗?
Any ideas? Is this possible with javascript?
谢谢.
推荐答案
您的问题的答案是是",但我认为您的问题没有准确描述您想要做的事情.您希望 letters.a
引用变量my_a",就可以使用 &
运算符在 C++ 中执行的操作而言.这在 JavaScript 中是不可能的.
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.a
to 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.
在声明中:
my_a = new Object('c');
您给my_a"一个新的、不同的值.因此, letters.a
仍然指的是它所做的相同的事情,而my_a"已经改变了.没有办法让一个变量或对象属性跟踪"另一个(在 JavaScript 中).
you're giving "my_a" a new, different value. Thus, letters.a
still 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).
编辑 —实际上,我发现您可以通过为字母"的a"属性定义一个getter"来执行您正在寻找的操作,该属性返回my_a"的当前值.它需要您正在使用的 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:
var letters = {};
Object.defineProperty(letters, "a", {
get: function() { return my_a; },
set: function(v) { my_a = v; }
});
不幸的是,IE9 之前的 IE 不支持.这是更新后的 jsfiddle.
IE before IE9 doesn't support that unfortunately. Here's the updated jsfiddle.
这篇关于是否有可能有 2 个变量指向同一个对象?(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!