2

我想通过引用对象 a3来设置值。a.b

例子:

var a ={};
a.a =1;
a.b =2;
var x = a.b;
alert (a.b);// show 2
x =3;
alert (a.b); // I want to see in this line 3 instead 2.

非常感谢

我怎么能做到这一点?

4

5 回答 5

2

You can't do that. Since 2 is a primitive, you don't have a reference to it, instead x actually has the value 3.

What you can do is to provide a function that will modify the property of the parent object:

var a = {
   a: 1,
   b: 2,
   setB: function(value) {
      this.b = value;
   }
}

a.setB(3);
console.log(a.b);

I think this is cleaner.

To answer your edit, yes, sort of. It depends what you're doing. If you had the following:

var a = {
   a: {value: 1},
   b: {value: 2},
};

var x = a.b;
x = {value: 3};

Then a.b would still be {value: 2}, because all you have done is made x point to a different object. But realize that x points to a.b, which is an object, so instead, if you do x.value = 3;, a.b now has {value: 3}.

于 2013-04-16T17:29:31.930 回答
1

你在 JavaScript 中没有指针,所以你不能简单地这样做。

您通常在 JavaScript 中“替换”指针的方法是使用回调:

var a ={};
a.a =1;
a.b =2;
var x = a.b;
alert (a.b);// show 2
var f = function(v){ a.b=v};
f(3);
alert (a.b); // alerts 3

这个回调可以传递给其他函数,并且可能是最接近你在这种语言中想要的。

于 2013-04-16T17:31:40.593 回答
1

您只能通过引用传递对象。

var a = {};
a.a = 1;
a.b = 2;
var x = a;
alert (a.b); // 2
x.b = 3;
alert (a.b); // 3

演示

于 2013-04-16T17:33:57.987 回答
0

当您想要传递对值的引用时,您总是可以使用装箱。现实情况是,您的业务案例将决定什么最适合您。

什么是装箱和拆箱,权衡取舍是什么?

这是一些未经测试的伪代码,但它应该适合您。

您有几个选择,将整个对象视为参考,或者仅对单个原始值进行装箱。

var c={}
c.a = null
c.b = null

//set the value of "c"
c = a;

//change the value of the reference
a.b = 100;

//now the reference has been update
alert( c.b );  // equals 100

或者,如果您只想将 int 装箱

var boxed_value = {}
boxed_value.total = 100;

var obj_a = {};
obj_a.value_a = boxed_value;

//obj_a.value_a.total = 100;


var obj_b = {};
obj_b.value = boxed_value;

//obj_b.value_a.total = 100
//obj_a.value_a.total = 100

boxed_value.total = 200;
obj_a.value.total = 300;
obj_b.value.total = 400;

//now all values have changed as they are referenced
于 2013-04-16T17:51:11.783 回答
0

再举一个例子

 var a ={};
    a.a =1;
    a.b =2;
    var x =function(v){ a.b=v};
    alert (a.b);// show 2
    x(3);
    alert (a.b); 
于 2013-04-16T17:37:44.963 回答