JavasScript中变量词法作用域:也叫做静态作用域,变量的作用域是在定义时决定而不是执行时决定。即词法作用域取决于源码,通过静态分析就能确定。
function f(){ var t = 'a'; return function fn(){ alert(t) alert(this.t); var t = 123; alert(t); alert(this.t); //this == window对象 }; } f()()
fn = { a: 1, b: function(){ console.info(a); console.info(this.a); }, c: function(){ var t = 1; var _this = this; //var a = 1; //local scope (1) //a = 123; //golble scope (2) return function(){ console.info(t); //闭包scope情况 //this == window对象,当(1)处放开时this.a返回undefined,(2)放开时返回123 console.info(this.a) console.info(_this.a) } } }; fn.c()()
在执行Test()时,此时的上下文对象是window,即Javascript的全局对象,在执行new Test();时新建了一个Object,此时执行Test函数的上下文对象就是Object。
function Test() { console.log(this); } Test(); //window new Test();//Object
参考:
http://www.jb51.net/article/25248.htm
http://mzhou.me/?p=81001#more-81001
1 楼
libmw
2010-12-01
建议楼主以后写alert或者document的时候把运行结果写在后边,这样方便广大朋友们看到结果是否跟他们预期的一样也便于讨论,比如:
<script type="text/javascript">
function f(){
var t = 'a';
return function fn(){
alert(t) //undefined
alert(this.t); //this == window对象 所以结果为undefined
var t = 123;
alert(t); //123
alert(this.t); //this == window对象 所以结果为undefined
};
}
f()()
</script>
<script type="text/javascript">
function f(){
var t = 'a';
return function fn(){
alert(t) //undefined
alert(this.t); //this == window对象 所以结果为undefined
var t = 123;
alert(t); //123
alert(this.t); //this == window对象 所以结果为undefined
};
}
f()()
</script>

2 楼
deng131
2010-12-01
下次注意
