为什么这个===窗口在JavaScript范围安全构造函数中是假的?

时间:2012-09-07 03:53:07

标签: javascript constructor window this

我的代码是:

(function(){
    var test=function(){
        if(this === window)
            return new test();
    }

    test.prototype.play = function(){
        alert("Hello");
    };

    window.Test=test;
})();

window.onload=function(){
    Test().play();
};

这可以在IE9+ firefox chrome中正常运行,但在ie 6/7/8中,Test().play();中出现错误,谁可以告诉我原因?

错误信息是:

enter image description here

1 个答案:

答案 0 :(得分:0)

IE有一些函数表达式的怪癖,考虑一下(未在IE 8中测试,因为我目前没有它):

(function(global){

    function test() {
        if (this === global)
            return new test();
    }

    test.prototype.play = function(){
        alert("Hello");
    };

    global.Test = test;

})(this);

window.onload = function(){
    Test().play();
};

另一种测试是:

    if (!(this instanceof Test))