Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an object inside another object fails in IE8

I want to implement a sort of a singleton object (About in the example below), which by itself is inside another object (Main).

This is my code. It works in every major browser (Firefox, Chrome and even IE9) but not in IE8. In IE8, the call to main.About.doSomething(); throws 'Object doesn't support this property or method'.

I also jsFiddled my code here: http://jsfiddle.net/c3URh/12/

What do I need in order to get it to work in IE8?

Note: I can call main.About().doSomething() and it will work in IE8, but won't work in other browsers, and anyway it's incorrect from OOP perspective.

My buggy code:

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();
}
​
like image 245
Erel Avatar asked May 26 '26 10:05

Erel


2 Answers

IE8 does not support Object.defineProperty. So, the catch block's code is executed. In that block, you did not define a proper replacement for the About getter.

This (inside catch) is a function:

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

While you expecte it to be an instance of About. IE8 doesn't support getters, so you have to use another method. The closest you can get is:

    this.About = about == undefined ? new About() : about;
like image 159
Rob W Avatar answered May 31 '26 17:05

Rob W


Is that not because the defineProperty fails and therefore there is no About to add to? IE8 has only partial support for defineProperty which you could find via google or SO search: 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

like image 29
mplungjan Avatar answered May 31 '26 18:05

mplungjan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!