用JavaScript指针? [英] Pointers in JavaScript?

查看:97
本文介绍了用JavaScript指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们可以在函数中传递一个不可变作为参数的变量的引用吗?

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指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆