JavaScript中的全局变量到局部变量 [英] Global variable to local variable in JavaScript

查看:70
本文介绍了JavaScript中的全局变量到局部变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道全局变量是在函数外部声明时创建的(例如 W3Schools )

I know global variables are created when they are declared outside a function (says W3Schools).

如果我创建一个全局变量并在函数中对其进行编辑,它会变成局部变量吗?函数给定的新值会变成全局值吗?

If I create a global variable and edit it in a function, does it become local? Does the new value given by the function become the global value?

推荐答案

通常,不,编辑全局变量不会使其成为本地变量:

In general, no, editing a global does not make it local:

var myglob = 5;
function incGlob() {
    myglob = myglob + 1;
}

incGlob();
console.log(myglob); // is 6 now

但是,如果您将全局变量作为参数传递,则该参数是本地副本:

However, if you pass the global variable as an argument, the argument is a local copy:

var myglob = 5;
function incArg(myloc) {
    myloc = myloc + 1;
}

incArg(myglob);
console.log(myglob); // is still 5

请注意,对象是通过引用传递的,因此,编辑参数变量的成员变量会更改传入的原始对象的成员变量:

Note that objects are passed by reference, so editing the member variables of an argument variable changes the member variables of the original object passed in:

var myglob = { foo:5 };
function editLoc(myloc) {
    myloc.foo = 6;
}

editLoc(myglob);
console.log(myglob.foo); // foo is 6 now

最后,请注意上面的 editLoc 中的局部变量只是一个参考.如果我们尝试覆盖整个对象(而不是成员变量),则该函数只会丢失对原始对象的引用:

Finally, note that the local variable in editLoc, above, is just a reference. If we try to overwrite the entire object (instead of a member variable), the function simply loses the reference to the original object:

var myglob = { foo:5 };
function clobberLoc(myloc) {
    myloc = { bar:7 };
}

clobberLoc(myglob);
console.log(myglob.foo); // myglob is unchanged...
// ...because clobberLoc didn't alter the object,
// it just overwrote its reference to the object stored in myglob 

这篇关于JavaScript中的全局变量到局部变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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