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();
}
IE8 does not support
Object.defineProperty. So, thecatchblock’s code is executed. In that block, you did not define a proper replacement for theAboutgetter.This (inside
catch) is a function: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: