ITeye博客

Javascript变量作用域问题

deng131 · 2010-12-01 10:49 · javascript · Web前端 · Markdown

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

评论(2)

  1. #2 楼 · deng131 · 2010-12-01 21:41

    下次注意 :idea:

  2. #1 楼 · libmw · 2010-12-01 16:56

    建议楼主以后写alert或者document的时候把运行结果写在后边,这样方便广大朋友们看到结果是否跟他们预期的一样也便于讨论,比如:

    :D

评论功能维护中,当前仅展示历史评论。