首页 新闻 会员 周边

IE6/7/8中JavaScript的安全构造函数问题请教?

0
悬赏园豆:50 [已关闭问题] 关闭于 2012-09-11 08:07

下面这段代码是安全构造函数的写法,但在IE6/7/8中不能运行:

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

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

    window.Test=test;
})();

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

改为:

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

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

    window.Test=test;
})();

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

就可以了,请问第一种写法为什么不行呢?

artwl的主页 artwl | 专家六级 | 园豆:16736
提问于:2012-09-07 11:43
< >
分享
所有回答(1)
0
this.constructor ===window.constructor貌似也不对,运行代码发现IE下两个constructor都是undefined。。
向往-SONG | 园豆:4853 (老鸟四级) | 2012-09-07 14:04

是的,现在只好改用:

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

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

    window.Test=test;
})();

window.onload=function(){
    Test().play();
};
支持(0) 反对(0) artwl | 园豆:16736 (专家六级) | 2012-09-07 14:05
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册