【问题标题】:Initializing an object inside another object fails in IE8在 IE8 中初始化另一个对象内的对象失败
【发布时间】:2012-02-15 17:42:17
【问题描述】:

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

这是我的代码。它适用于所有主流浏览器(Firefox、Chrome 甚至 IE9),但不适用于 IE8。在 IE8 中,对 main.About.doSomething(); 的调用会抛出“对象不支持此属性或方法”。

我也在这里修改了我的代码: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();
}
​

【问题讨论】:

    标签: javascript oop internet-explorer-8 properties singleton


    【解决方案1】:

    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;
    

    【讨论】:

      【解决方案2】:

      这不是因为defineProperty 失败,因此没有About 可以添加吗? IE8 仅对 defineProperty 提供部分支持,您可以通过 google 或 SO 搜索找到:Working around IE8's broken Object.defineProperty implementation

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

      【讨论】:

        【解决方案3】:

        在 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/

        【讨论】:

          猜你喜欢
          • 2016-05-30
          • 2011-10-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-16
          • 2016-12-18
          • 2022-11-20
          相关资源
          最近更新 更多