Help get this topic noticed by sharing it on Twitter, Facebook, or email.
I’m confused

Singleton not working in IE8 as described in the Javascript Patterns book on page 144.

Hi,

I have a few question about the Singleton Pattern from the JavaScript Patterns book and its compatibility with IE8. I am trying to use the following Singleton pattern:

function Universe() {
    // the cached instance
    var instance;
    // rewrite the constructor
    Universe = function Universe() {
        return instance;
    };
    // carry over the prototype properties
    Universe.prototype = this;
    // the instance
    instance = new Universe();
    // reset the constructor pointer
    instance.constructor = Universe;
    // all the functionality
    instance.start_time = 0;
    instance.bang = "Big";

    return instance;
}

But the following Jasmine tests are failing in IE8:

describe("Singleton Test Suite", function () {
    iit('can create valid singleton', function () {
        // update prototype and create instance
        Universe.prototype.nothing = true; // true
        var uni = new Universe();
        expect(uni).toBeDefined();
        Universe.prototype.everything = true; // true
        var uni2 = new Universe();
        expect(uni2).toBeDefined();
        // it's the same single instance
        expect(uni === uni2).toBe(true); // true
        // all prototype properties work
        // no matter when they were defined
        //expect(uni.nothing && uni2.nothing).toBe(true); // true
        //expect(uni.everything && uni2.everything).toBe(true); // true
        // the normal properties work
        //expect(uni.bang).toBe("Big"); // "Big"
        // the constructor points correctly
        //expect(uni.constructor).toBe(Universe);
    });
});
My test fails at the following line from the above Jasmine test: "expect(uni === uni2).toBe(true);"; but Jasmine reports that they are not equal.

Does anybody know why these two instances of Universe are not equal to each other in IE8?

Thank you.

Tonté
1 person has
this question
+1
Reply