3

我的代码是:

(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();,谁能告诉我为什么?

错误信息是:

在此处输入图像描述

4

1 回答 1

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))
于 2012-09-07T05:55:32.697 回答