Heim  >  Artikel  >  Web-Frontend  >  JavaScript 变量作用域分析_javascript技巧

JavaScript 变量作用域分析_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:05:13967Durchsuche
复制代码 代码如下:

/* 代码1 */
var scope = "global ";
function checkScope() {
var scope = "local ";
function childCheck() {
var scope = "childLocal ";
document.write(scope);
}
function childUndefined() {
document.write(scope);
var scope;
}
function childOverride() {
scope = "childOverride ";
document.write(scope);
}
document.write(scope); //输出"local"
childCheck(); //输出"childLocal"
childUndefined(); //输出"undefined"
childOverride(); //输出"childOverride"
document.write(scope); //输出"childOverride"
}
checkScope(); //输出"local childLocal undefinedchildOverride childOverride"
document.write(scope); //输出"global "

全局作用域与局部作用域
全局(global)变量的作用域是全局的,在Javascript中处处有定义;而函数内部声明的变量是局部(local)变量,其作用域是局部性的,只在函数体内部有定义。对于下面的输出读者应不会感到意外。
复制代码 代码如下:

/* 代码2 */
var scope = "global";
function checkScope() {
var scope = "local";
document.write(scope);
}
checkScope(); //输出"local"
document.write(scope); //输出"global"

全局变量作用域中使用变量可以不用var语句,但在声明局部变量是一定要使用var语句,否则会视为对全局变量的引用。看下面代码:
复制代码 代码如下:

/* 代码3 */
var scope = "global";
function checkScope() {
scope = "local";
document.write(scope);
}
checkScope(); //输出"local"
document.write(scope); //输出"local"

没有块作用域
Javascript没有块级作用域,函数中声明的变量在整个函数中都是有定义的。对于下面的代码对于生疏的读者可能颇感意外:
复制代码 代码如下:

/* 代码4 */
var scope = "global";
function checkScope() {
document.write(scope); //语句4.1
var scope = "local"; //语句4.2
document.write(scope);
}
checkScope(); //输出"undefinedlocal"

由于语句4.1(var scope = "local";)声明的变量在整个checkScope函数作用域内都有效,因此在语句4.2(document.write(scope); )执行的时scope引用的是局部变量,而此时局部变量scope尚未定义,所以输出”undefined”。因此一个好的编程习惯是将所有的变量声明集中起来放在函数的开头。

在了解了上述内容之后,读者再看看代码1应该不会感到困惑了。

对象的属性变量
对象的属性变量比较容易理解,看一下下面的代码读者应该不会感到疑惑。
复制代码 代码如下:

/* 代码5 */
var scope = "global ";
var obj = new Object();
obj.scope = "object ";
obj.checkScope = function () {
var scope = "loacl ";
document.write(scope); //输出"loacl"
document.write(this.scope); //输出"object"
document.write(window.scope); //输出"global"
}
obj.checkScope(); //输出"loacl object global"
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn