问题描述
我们可以在函数中传递一个不可变作为参数的变量的引用吗?
Can we pass a reference of a variable that is immutable as argument in a function?
示例:
var x = 0;
function a(x)
{
x++;
}
a(x);
alert(x); //Here I want to have 1 instead of 0
推荐答案
由于JavaScript不支持通过引用传递参数,因此您需要将变量改为对象:
Since JavaScript does not support passing parameters by reference, you'll need to make the variable an object instead:
var x = {Value: 0};
function a(obj)
{
obj.Value++;
}
a(x);
document.write(x.Value); //Here i want to have 1 instead of 0
在此case, x
是对象的引用。当 x
传递给函数 a
时,该引用被复制到 obj
。因此, obj
和 x
在内存中引用相同的东西。更改 obj
的 Value
属性会影响 Value
属性 x
。
In this case, x
is a reference to an object. When x
is passed to the function a
, that reference is copied over to obj
. Thus, obj
and x
refer to the same thing in memory. Changing the Value
property of obj
affects the Value
property of x
.
Javascript将始终按值传递函数参数。这只是语言的规范。你可以在两个函数的本地范围内创建 x
,而不是传递变量。
Javascript will always pass function parameters by value. That's simply a specification of the language. You could create x
in a scope local to both functions, and not pass the variable at all.
这篇关于用JavaScript指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!