在IE8中初始化另一个对象内部的对象失败

Initializing an object inside another object fails in IE8

本文关键字:内部 对象 失败 一个对象 IE8 初始化      更新时间:2023-09-26

我想实现一种单例对象(以下示例中为About),它本身就在另一个对象(Main)内部。

这是我的密码。它适用于所有主流浏览器(Firefox、Chrome甚至IE9),但不适用于IE8。在IE8中,对main.About.doSomething();的调用引发"Object不支持此属性或方法"。

我还在这里jsFiddle了我的代码:http://jsfiddle.net/c3URh/12/

我需要什么才能让它在IE8中工作?

注意:我可以调用main.About().doSomething(),它将在IE8中工作,但在其他浏览器中不工作,无论如何,从OOP的角度来看,这是不正确的。

我的错误代码:

function About(){
    this.doSomething = function(){
        alert('a');
    };
}
function Main(){
    var about;
    try {
    Object.defineProperty(this, 'About', {
            get: function () {
                if (about == undefined) {
                    about = new About();
                }
                return about;
            }
        });
    }
    catch (e) {
        // this code does not work in ie8. Throwing 'Object doesn't support this property or method'
        this.About = function() {
            if (about == undefined) {
                about = new About();
            }
            return about;
        };
    }
}
function clickMe()
{
    var main = new Main();
    main.About.doSomething();
}
​

IE8不支持Object.defineProperty。因此,执行catch块的代码。在该块中,您没有为About getter定义合适的替换。

这(在catch内部)是一个函数:

    this.About = function() {
        if (about == undefined) {
            about = new About();
        }
        return about;
    };

而您期望它是About的一个实例。IE8不支持getter,所以您必须使用另一种方法。你能得到的最接近的是:

    this.About = about == undefined ? new About() : about;

这不是因为defineProperty失败,因此没有About添加吗?IE8对defineProperty只有部分支持,你可以通过谷歌或SO搜索找到:围绕IE8';s损坏的Object.defineProperty实现

http://blogs.msdn.com/b/ie/archive/2010/09/07/transitioning-existing-code-to-the-es5-getter-setter-apis.aspx

IE9之前没有getter,这段代码看起来真的很有趣。使用getter实例化一个私有变量,并添加一个检查,使其只在第一次执行?这就是构造函数的作用。

function About(){
    this.doSomething = function(){
        alert('a');
    };
}
function Main(){
    this.About = new About();
}
var main = new Main();
main.About.doSomething();  // alerts 'a'

这并不能解决如何在IE8及以下版本中实现getter的问题,但无论如何,使用它的方式很糟糕

http://jsfiddle.net/mendesjuan/zPq4v/