1、全局变量
var scope = "global";
function f() {
alert(scope); // global
}
f();
2、局部变量被 hoisted
var scope = "global";
function f() {
alert(scope); // undefined
var scope = "local";
}
f();
3、强制访问外部域
var scope = "global";
function f() {
alert(this.scope); // global
var scope = "local";
}
f();
4、外部变量被隐藏
var scope = "global";
function f() {
var scope = "local";
alert(scope); // local
}
f();
5、外部变量被修改
var scope = "global";
function f() {
scope = "local";
alert(scope); // local
}
f();
alert(scope); // local
相当于
var scope = "global";
function f() {
this.scope = "local";
alert(scope); // local
}
f();
alert(scope); // local
6、函数被当成 构造方法使用
var scope = "global";
function f() {
this.scope = "local"; // 这里的this 变了
alert(scope); // global
}
f1 = new f(); // f 被当成 constructor 使用
alert(f1.scope); // local
alert(scope); // global
本文探讨了JavaScript中全局变量、局部变量的作用域行为,包括变量提升、外部变量的隐藏与修改等现象,并展示了如何通过构造函数改变变量的访问方式。
912

被折叠的 条评论
为什么被折叠?



