【发布时间】: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