在 Javascript 中,这个参数是如何通过值而不是通过引用传递的? [英] In Javascript, how is this argument passed by value and not by reference?

查看:24
本文介绍了在 Javascript 中,这个参数是如何通过值而不是通过引用传递的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力思考传递参数"的想法.在我正在阅读的一本书中,它指出参数仅按值传递,而不是按引用传递.

I am trying to wrap my head around this idea of 'argument passing.' In a book I am reading it states that arguments are only passed by value not by reference.

function addTen(num) { 
   num + = 10;
   return num; 
} 


var count = 20; 
var result = addTen(count); 
alert(count); // 20 - no change 
alert(result); // 30

上面的例子很清楚,但下面的例子让我很困惑.

The example above is pretty clear, but the example below leaves me very confused.

当person传递给setName函数时,是不是映射了局部变量'obj'并向下流动函数中的语句?即person首先被设置为属性名称,然后它被分配给一个新的对象,最后这个新创建的人对象被分配属性'Gregg'????

When person is passed to the setName function, doesn't it mirror the local variable 'obj' and flow down the statements in the function? i.e. person is first set to the property name, then it's assigned to a new Object, and finally this new created person object is assigned the property 'Gregg'????

为什么你会得到尼古拉斯"!!!!

Why do you get 'Nicholas'!!!!

function setName(obj) {
    obj.name = "Nicholas"; 
    obj = new Object(); 
    obj.name = "Greg"; 
}        

var person = new Object(); 
setName(person); 
alert(person.name); //" Nicholas"

推荐答案

对象被传递给函数作为引用的副本.现在您的示例中会发生什么:

Objects are passed to function as a copy of the reference. Now what happens in your example is next:

var person = new Object();     

function setName(obj) { // a local obj* is created, it contains a copy of the reference to the original person object
    obj.name = "Nicholas"; // creates a new property to the original obj, since obj here has a reference to the original obj
    obj = new Object(); // assigns a new object to the local obj, obj is not referring to the original obj anymore
    obj.name = "Greg"; // creates a new property to the local obj
}

setName(person);
alert( person.name); //" Nicholas"

* = obj 是一个局部变量,包含一个,它是对原始<代码>对象.当您稍后更改局部变量时,它不会反映到原始对象.

* = obj is a local variable containing a value, which is a reference to the original obj. When you later change the value of the local variable, it's not reflecting to the original object.

这篇关于在 Javascript 中,这个参数是如何通过值而不是通过引用传递的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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