在JavaScript中通过引用/值传递什么?

时间:2015-02-13 05:49:04

标签: javascript

我对JavaScript如何决定值和引用传递的内容感到困惑,所以我试图通过编写一些测试来弄清楚它。结果让我更加困惑。任何人都可以解释解释器如何决定变量是否通过val / ref在此代码中传递?另外,您知道如何通过引用显式传递变量吗?

function test(str, obj1, obj2, arr1, arr2) {
    str = "Str was passed by reference!";

    obj1.val = "Obj1 was passed by reference!";
    obj2 = {val: "Obj2 was passed by reference!"};

    arr1[0] = 'r';
    arr1[1] = 'e';
    arr1[2] = 'f';

    arr2 = "arr2 was passed by reference!".split('');
}

var str = "Str was passed by value!";
var obj1 = {val: "obj1 was passed by value!"};
var obj2 = {val: "obj2 was passed by value!"}

var arr1 = ['val'];
var arr2 = "arr2 was passed by value!".split('');

test(str, obj1, obj2, arr1, arr2);
console.log(str);
console.log(obj1);
console.log(obj2);
console.log('arr1 was passed by ' + arr1.join(''));
console.log(arr2.join(''));

此代码记录:

Str was passed by value!
Object {val: "Obj1 was passed by reference!"}
Object {val: "obj2 was passed by value!"}
arr1 was passed by ref
arr2 was passed by value!

谢谢:)

如果您希望看到它,请将此代码放在JSFiddle上。

- 编辑 -

对于上下文,我最初试图通过引用显式传入大对象/基元。

1 个答案:

答案 0 :(得分:1)

您的测试代码是错误的。 在你看到你是"通过引用",这并不意味着你是"通过引用",它意味着你正在改变内容 of object / array,而不是对象引用本身。

你看到的是"传递价值",因为你设定的价值没有改变。

当您分配 strobj2arr2时(您的代码所说的是"按值"),您正在内部作用域参数变量上设置新参考。你没有改变外面的。因此,当您打印它(在test函数之外)时,它只保留它所分配的值。

同样地,你看到的那些通过"通过引用",你只是改变他们的属性,"内容"变量。如果你这样做:

obj1.val = "Obj1 was passed by reference!";

然后你要设置" val"而不是" obj1"。这就是为什么你看到它发生变化"外面"。 或者当你这样做时:

arr1[0] = 'r';
arr1[1] = 'e';
arr1[2] = 'f';

您正在设置" arr1"的元素0," arr1"的元素1等,而不是" arr1"。

所以你的代码并没有证明你所认为的证据。

在某些情况下,您正在改变对象,并在其他情况下分配不同的对象,这是您所看到的实际差异,而不是"通过引用或值传递"。

顺便说一句,Javascript无法通过引用传递#34;以你想要的方式。您不能只设置范围的参数变量值并假装它在该范围之外更改。其他语言允许您这样做,但不允许Javascript。您将参数(指针)传递给参数内容中的对象,但参数本身与您传入的"变量没有任何关系(除了它们最初指向的同一个对象)