美文网首页
js参数是按值传递的

js参数是按值传递的

作者: 阿昕_ | 来源:发表于2018-06-25 14:35 被阅读6次

    起源

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

    相关文章

      网友评论

          本文标题:js参数是按值传递的

          本文链接:https://www.haomeiwen.com/subject/pgcyyftx.html