在Javascript中,这是怎么参数按值传递而不是参考? [英] In Javascript, how is this argument passed by value and not by reference?

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

问题描述

我试图环绕这个想法我的头'参数传递。在一本书我读它指出参数只能按值传递而不是按引用。

 函数addTen(NUM){
   NUM + = 10;
   返回NUM;
}
变种数= 20;
VAR的结果= addTen(计数);
警报(计数); // 20 - 无变化
警报(结果); // 30

上面的例子是pretty清楚,但下面的例子让我非常困惑。

当人被传递给的setName功能,不是镜像局部变量OBJ
并流下来函数中的语句?
即人首先设置为属性名,那么它分配给新的对象,最后这个新创建的Person对象被分配属性格雷格????

为什么你'尼古拉'!!!!

 函数的setName(OBJ){
    obj.name =尼古拉斯
    OBJ =新的对象();
    obj.name =格雷格;
}变种人=新的对象();
的setName(人);
警报(person.name); //尼古拉斯


解决方案

对象传递给充当的引用的副本的。现在什么对你发生的例子接下来是:

 变种人=新的对象();功能的setName(OBJ){//创建一个本地的obj *,它包含了引用的副本到原来的OBJ
    obj.name =尼古拉斯 //创建一个新的属性到原来的OBJ,因为这里的obj有原来的OBJ参考
    OBJ =新的对象(); //分配一个新对象到本地物镜,物镜是不是指原始物镜再
    obj.name =格雷格; //创建一个新的属性,以当地的obj
}的setName(人);
警报(person.name); //尼古拉斯

* = OBJ 局部变量的包含的的,这是原来的 OBJ 的参考。当你以后改变的的的的局部变量的,它没有反映到原来的对象。

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.

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 you 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 obj
    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 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天全站免登陆