如何在javascript中创建指向对象属性的指针? [英] How do you create a pointer to an object property in javascript?
问题描述
如果我有这样的对象:
obj = {a:{aa:1}, b:2};
我想创建一个快捷方式变量(指向obj.a.aa的指针),如下所示:
and I want to create a shortcut variable (pointer to obj.a.aa) x like this:
x = obj.a.aa;
然后我想像这样使用x将值3分配给obj.a.aa:
and then I want to assign the value 3 to obj.a.aa using x like this:
x = 3; // I would like for obj.a.aa to now equal 3
console.log(obj.a.aa); // 1 (I want 3)
如何设置x以使值3进入obj.a.aa?
How can I set x up to result in the value 3 going into obj.a.aa?
我了解obj.a.aa是原始类型,但是如何定义指向它的变量,然后可以使用该变量为属性分配值?
I understand that obj.a.aa is a primitive, but how can I define a variable that points to it which I can then use to assign a value to the property?
推荐答案
您不能使用x = value,因为它不会保留任何引用,而只是保留副本.为此,您必须引用父分支:
You cannot use x = value as that will not keep any references, just a copy. You would have to reference the parent branch in order to do so:
x = obj.a;
然后设置值:
x.aa = 3;
这篇关于如何在javascript中创建指向对象属性的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!