了解本地范围 [英] Understanding Local Scope
本文介绍了了解本地范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
无论我怎么努力,我都无法改变'i'的价值......
I can't manage to change the value of 'i' no matter how hard I try...
我的代码如下:
function changeValue(){
//neither 'var i=99;' or 'i=99;' interferes with the 'i' on myFunction
}
function myFunction(){
var i;
for(i=0;i<3;i++){
alert(i);
changeValue();
alert(i);
}
}
myFunction();
我的问题:如何更改'i'的值(在上MyFunction )使用 changeValue 函数?
My question: How can I change the value of 'i' (on MyFunction) using the changeValue function?
另外:我非常需要阅读一些关于此的指南,可能有人给我一个好的链接?
Also: I badly need read some guides about this, could someone give me a link to a good one?
推荐答案
移动 changeValue()
与 i
相同的范围:
function myFunction(){
var i;
for(i=0;i<3;i++){
alert(i);
changeValue();
alert(i);
}
function changeValue() { i = 99; }
}
或者,放 i
与相同的范围changeValue()
:
var i;
function changeValue() { i = 99; }
function myFunction(){
// var i; // don't define i here
for(i=0;i<3;i++){
alert(i);
changeValue();
alert(i);
}
}
或者,您可以告诉 changeValue()
i
的值是什么,然后让它返回新值:
Alternatively, you can tell changeValue()
what the value of i
is, then have it return the new value:
function changeValue(i) {
return i + 1;
}
然后:
i = changeValue(i);
编辑:说明范围:
var a = 0; // global scope - accessible everywhere via a
// unless overridden by a locally scoped a
// always accessible via window.a
function doSomething () {
var a = 1; // local scope - you can still access window.a
var b = 2; // local scope - accessible to child scopes, but not global scope
function innerFunction () {
var a = 3; // you no longer have access to the parent function's a variable
// you can still access window.a
var c = 4; // only accessible here (since no child scopes exist)
alert(window.a); // 0
alert(a); // 3
alert(b); // 2
alert(c); // 4
}
innerFunction();
alert(window.a); // 0
alert(a); // 1
alert(b); // 2
alert(c); // undefined - unavailable in this scope
}
doSomething();
alert(window.a); // 0
alert(a); // 0
alert(b); // undefined - unavailable in this scope
alert(c); // undefined - unavailable in this scope
这篇关于了解本地范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文