JS Global Variable to Local Variable

只谈情不闲聊 提交于 2019-12-02 06:12:56

问题


This is a simple question.

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

My question is, 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?


回答1:


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

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 



回答2:


No, editing the global variable will not change the variable's scope. The new value assigned becomes the global value.

http://jsfiddle.net/RtnaB/

myGlobal = 'foo'; // notice no 'var' keyword, implicitly global (DON'T DO THIS)

console.log(myGlobal); // logs 'foo'

var myFunc = function () {
    myGlobal = 'bar';
};

myFunc();

console.log(myGlobal); // logs 'bar'



回答3:


Yes.

You will only create a local variable if you use the var keyword to declare it inside a function.




回答4:


The new value becomes the global value.



来源:https://stackoverflow.com/questions/10887291/js-global-variable-to-local-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!