js参数是按值传递的

起源

function setName( obj ){
  obj.name = 'A';
}
let  man = new Object();
setName(man);
console.log(man.name);   // A

通过上述代码段,可以看出,在局部作用域中修改的对象,会在全局作用域中体现出来。对于接触过C++的我来说,我的第一反应是这个参数是按引用传递的,可是事实却是按值传递的,到底是怎么回事呢??对于基本类型按值传递没有任何可争议的,所以接下来只探索对象按值传递这个问题。

探索

接着再看下边的代码:

function setName( obj ){
  obj.name = 'A';
  obj = new Object();
  obj.name = 'B';
}
let  man = new Object();
setName(man);
console.log(man.name);   // A

问题来了,如果是按引用传值的,那么man将会由于 obj = new Object();这行代码而指向新的对象,打印出来的man.name应该是B,事实打印出的是A,这起码说明了参数是对象时并不是按引用传值的。

现在,要说一下call by sharing(共享传值),解释如下:
The main point of this strategy is that function receives the copy of the reference to object. This reference copy is associated with the formal parameter and is its value.
Regardless the fact that the concept of the reference in this case appears, this strategy should not be treated as call by reference (though, in this case the majority makes a mistake), because the value of the argument is not the direct alias, but the copy of the address.
The main difference consists that assignment of a new value to argument inside the function does not affect object outside (as it would be in case of call by reference). However, because formal parameter, having an address copy, gets access to the same object that is outside (i.e. the object from the outside completely was not copied as would be in case of call by value), changes of properties of local argument object — are reflected in the external object.

可以很清楚的看到,共享传值传递的是对象的引用的拷贝。而js中使用对象进行传参时,确切的说是按共享传值的,也就是说,上述代码中,man是对象的一个地址,而obj则是man的一个拷贝。由于obj里也存储着初始对象的地址,所以内部进行obj.name = ‘A’的操作的时候,会影响到外部的对象,这一现象并不是因为按引用传值所导致的。

代码段的图示如下:

共享传值

结语

  • 参数是基本类型:按值传递 。
    被传递的值会被复制给一个局部变量(arguments对象中的一个元素)
  • 参数如果是引用类型:按共享传递。
    被传递的值在内存中的地址复制给一个局部变量,但是由于拷贝副本也是一种值的拷贝,所以可以认为是按值传递。

个人链接

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值