javascript 对象是否通过引用或值传递 [英] does javascript objects passed by reference or value

查看:51
本文介绍了javascript 对象是否通过引用或值传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下代码,但它会提醒旧的对象名称属性?我知道对象是通过引用传递的,但它是通过引用传递的,那么在函数内部更改的对象也应该在函数外部更改,不是吗?

i tried this following code but it alerts the old object name property? i know that objects are passed by reference but its passed by reference then the object which is changed inside the function should also be change outside the function isn't it?

function setName(obj) {
 obj.name = "raziq";
 obj = new Object();
 obj.name = "abdul";
}
var person = new Object();
setName(person);
alert(person.name); //still yields raziq

我有点困惑,如果对象是通过引用传递的,那么应该提醒新名称,为什么它仍然提醒 raziq 作为对象的名称?

i am a bit confused if object is passed by reference then the new name should be alerted why is it still alert raziq as the name of the object ?

推荐答案

当您将 new Object() 分配给变量 obj 时,实际上并没有交换原始对象.计算机在内存中为您刚刚实例化的对象创建一个新位置,并为 name 属性分配一个值abdul",但这不会更改先前的对象,因为它驻留在内存中的不同位置.新创建的对象永远不会离开函数.

When you assign the new Object() to the variable obj, you're not actually swapping the original object. The computer creates a new spot in memory for the object you just instantiated and assigns the name property a value of "abdul", but that doesn't change the previous object, as it resides in a different spot in memory. The newly created object never leaves the function.

不要将 obj 变量视为容纳对象的容器,而是将其视为带有对象位置数字地址的占位符.当您将 person 传递给函数时,您传递的是地址,而不是对象本身.因此,在函数内部,当您创建新对象时,您将新对象的地址存储在占位符 obj 中.函数外的变量 person 仍然包含原始对象的地址,而不是您在函数中创建的新对象.

Instead of thinking of the obj variable as a container holding the object, think of it as a place holder with the numeric address of the location of the object. When you pass person in to the function, you're passing that address, not the object itself. So, inside of the function, when you create the new object, you're storing the address of that new object in the placeholder obj. The variable person outside the function still contains the address to the original object, not the new one you created in the function.

这篇关于javascript 对象是否通过引用或值传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆