日期:2014-05-16  浏览次数:20548 次

又是关于闭包的疑问,比较高级的疑问
JScript code

        var outwrap = function(){
            this.heihei = function(){
            };
            this.heihei.prototype = {
                b: (this.bb = function(){
                    var md = this;
                    return function(){
                        return md;
                    }
                })()
            };
        };
        var o = new outwrap();
        alert(o.bb);
        var h = new o.heihei();
        alert(h.b() == window);


h.b() == window结果为true,非常疑惑,为什么h.b()的结果不是o,而是window呢,哪位高人帮忙解惑一下,谢谢

------解决方案--------------------
sorry,不是'直接转',是本域找不到的变量,转到window域去找.
this并不在作用域链里查找,和使用到的变量要在作用域链中查找是不一样的

JScript code
var fn = function(){
  var a = 1;
  (function(){
      alert(a);//1
      alert(this) //window 
   })()
}
fn();

------解决方案--------------------
探讨
看了Objector的回复,我明白我的问题所在了:“首先要知道:任何立即执行的闭包【(function(){...})()的形式】,他的函数体内的this始终指向window”,我想原因应该就和前面几位说的一样,是因为这个匿名函数是一个匿名的全局变量,非常感谢各位

不过好像全局匿名的函数如此,局部的非匿名函数还是如此,这是为什么呢?
----------------------华丽的分割线,以下说的都是局部的非匿名函数----------
JScript codevar outwrap=function(){//局部变量aavar aa=function(){//局部变量fnvar fn=function(){//结果[object Window] alert(this);
};
(fn)();
};//局部变量bbvar bb=new aa();
};var o=new outwrap();
foolbirdflyfirst 在 12楼对此所说的“函数直接执行,内部的this,是哪来的呢?只好转到window域去了。输出window”,这又是为什么呢?
按我的理解,此时的scope chain应该是:bb->0->window,作用域怎么会直接转到window呢




------解决方案--------------------
关于this的最终回复,参见ECMA-262 10.2.3:


The caller provides the this value. If the this value provided by the caller is not an object (including the case where it is null), then the this value is the global object.


其他的参见Javascript Scope Chain相关资料。
------解决方案--------------------
应该会有人解答你的
走先