[color=blue]
JavasScript中变量词法作用域:也叫做静态作用域,变量的作用域是在定义时决定而不是执行时决定。即词法作用域取决于源码,通过静态分析就能确定。
[/color]
[color=darkblue]在执行Test()时,此时的上下文对象是window,即Javascript的全局对象,在执行new Test();时新建了一个Object,此时执行Test函数的上下文对象就是Object。[/color]
参考:
[url]http://www.jb51.net/article/25248.htm[/url]
[url]http://mzhou.me/?p=81001#more-81001[/url]
JavasScript中变量词法作用域:也叫做静态作用域,变量的作用域是在定义时决定而不是执行时决定。即词法作用域取决于源码,通过静态分析就能确定。
[/color]
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()()
[color=darkblue]在执行Test()时,此时的上下文对象是window,即Javascript的全局对象,在执行new Test();时新建了一个Object,此时执行Test函数的上下文对象就是Object。[/color]
function Test() {
console.log(this);
}
Test(); //window
new Test();//Object
参考:
[url]http://www.jb51.net/article/25248.htm[/url]
[url]http://mzhou.me/?p=81001#more-81001[/url]