Javascript变量作用域问题

[color=blue]
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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值