为对象分配其他内容时,为什么不通过引用传递此对象? [英] Why isn't this object being passed by reference when assigning something else to it?
本文介绍了为对象分配其他内容时,为什么不通过引用传递此对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道在JS中,对象是通过引用传递的,例如:
I know that in JS, objects are passed by reference, for example:
function test(obj) {
obj.name = 'new name';
}
var my_obj = { name: 'foo' };
test(my_obj);
alert(my_obj.name); // new name
但为什么以下不起作用:
But why doesn't the below work:
function test(obj) {
obj = {};
}
var my_obj = { name: 'foo' };
test(my_obj);
alert(my_obj.name); // foo
我已将对象设置为 {}
(空)但它仍然说 foo
。
I have set the object to {}
(empty) but it still says foo
.
任何人都可以解释这背后的逻辑吗? / p>
Can any one explain the logic behind this?
推荐答案
如果您熟悉指针,那么您可以采用类比。你实际上是在传递一个指针,所以 obj.someProperty
会取消引用该属性并实际覆盖它,而只是覆盖 obj
会杀死指针而不会覆盖对象。
If you are familiar with pointers, that's an analogy you can take. You're actually passing a pointer, so obj.someProperty
would dereference to that property and actually override that, while merely overriding obj
would kill off the pointer and not overwrite the object.
这篇关于为对象分配其他内容时,为什么不通过引用传递此对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文