按引用与按值划分的 JavaScript

我正在寻找一些很好的综合阅读材料,关于JavaScript何时按值传递某些内容,何时通过引用,何时修改传递的项目会影响函数外部的值,何时不传递。我还感兴趣的是,当赋值给另一个变量时,是通过引用还是按值,以及它是否遵循与作为函数参数传递不同的规则。

我已经做了很多搜索,并找到了很多具体的例子(其中许多是在SO上),从中我可以开始拼凑出真正规则的各个部分,但我还没有找到一个写得很好的文档来描述这一切。

另外,语言中是否有办法控制某些东西是通过引用还是通过价值传递的?

以下是我想了解的一些问题类型。这些只是例子 - 我实际上希望了解语言的规则,而不仅仅是对具体例子的答案。但是,这里有一些例子:

function f(a,b,c) {
   a = 3;
   b.push("foo");
   c.first = false;
}

var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);

对于所有不同类型的 x、y 和 z,何时在 f 的范围之外更改了内容?

function f() {
    var a = ["1", "2", "3"];
    var b = a[1];
    a[1] = "4";
    // what is the value of b now for all possible data types that the array in "a" might hold?
}

function f() {
    var a = [{yellow: "blue"}, {red: "cyan"}, {green: "magenta"}];
    var b = a[1];
    a[1].red = "tan";
    // what is the value of b now and why?
    b.red = "black";
    // did the value of a[1].red change when I assigned to b.red?
}

如果我想制作一个对象的完全独立的副本(没有任何引用),那么最佳实践方法是什么?


答案 1

我的理解是,这其实很简单:

  • Javascript总是按值传递,但是当变量引用对象(包括数组)时,“值”是对对象的引用。
  • 更改变量的值永远不会更改基础基元或对象,它只是将变量指向新的基元或对象。
  • 但是,更改变量引用的对象的属性确实会更改基础对象。

因此,通过一些示例:

function f(a,b,c) {
    // Argument a is re-assigned to a new value.
    // The object or primitive referenced by the original a is unchanged.
    a = 3;
    // Calling b.push changes its properties - it adds
    // a new property b[b.length] with the value "foo".
    // So the object referenced by b has been changed.
    b.push("foo");
    // The "first" property of argument c has been changed.
    // So the object referenced by c has been changed (unless c is a primitive)
    c.first = false;
}

var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false

示例 2:

var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4";   // a is now ["1", "4", {foo:"bar"}]; b still has the value
              // it had at the time of assignment
a[2] = "5";   // a is now ["1", "4", "5"]; c still has the value
              // it had at the time of assignment, i.e. a reference to
              // the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"

答案 2

Javascript 总是按值传递。但是,如果将对象传递给函数,则“value”实际上是对该对象的引用,因此该函数可以修改该对象的属性,但不会导致函数外部的变量指向某个其他对象

例如:

function changeParam(x, y, z) {
  x = 3;
  y = "new string";
  z["key2"] = "new";
  z["key3"] = "newer";

  z = {"new" : "object"};
}

var a = 1,
    b = "something",
    c = {"key1" : "whatever", "key2" : "original value"};

changeParam(a, b, c);

// at this point a is still 1
// b is still "something"
// c still points to the same object but its properties have been updated
// so it is now {"key1" : "whatever", "key2" : "new", "key3" : "newer"}
// c definitely doesn't point to the new object created as the last line
// of the function with z = ...