[英]Global variable to local variable in JavaScript
I know global variables are created when they are declared outside a function (says W3Schools ).我知道全局变量是在函数外部声明时创建的( 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
Finally, note that the local variable in editLoc
, above, is just a reference.最后,请注意上面
editLoc
中的局部变量只是一个引用。 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 becomes the global value.
分配的新值成为全局值。
http://jsfiddle.net/RtnaB/ 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'
Yes.是的。
You will only create a local variable if you use the var
keyword to declare it inside a function.如果您使用
var
关键字在函数内声明它,您只会创建一个局部变量。
新值成为全局值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.