最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Global variable to local variable in JavaScript - Stack Overflow

programmeradmin3浏览0评论

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 bee local? Does the new value given by the function bee the global value?

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 bee local? Does the new value given by the function bee the global value?

Share Improve this question edited Dec 21, 2020 at 18:28 Peter Mortensen 31.6k22 gold badges110 silver badges133 bronze badges asked Jun 4, 2012 at 19:42 apparatixapparatix 1,5127 gold badges22 silver badges37 bronze badges 1
  • Why dont you test it ? Keep it simple silly :) – Jashwant Commented Jun 4, 2012 at 19:45
Add a ment  | 

4 Answers 4

Reset to default 8

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 

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

http://jsfiddle/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'

Yes.

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

The new value bees the global value.

发布评论

评论列表(0)

  1. 暂无评论