0

Possible Duplicate:
Simplest/Cleanest way to implement singleton in JavaScript?

Here is a code snippest that tries to implement a singleton object.

Game.Score = (

    function () {
        ....
        var currentScorePolicy = {
            onBrickHitCorrectBasket: function () { alert("defaultScorePolicy::onBrickHitCorrectBasket called"); },
            onBrickHitWrongBasket: function () { },
            onBrickMissAllBaskets: function () { }
        };
        ...
        return {
             ....
             applyScorePolicyWithBonusEnabled: function (scorePerQuestion, maxBonusFactor) {
                currentScorePolicy = {
                    onBrickHitCorrectBasket: function () {
                       // alert("applyScorePolicyWithBonusEnabled::onBrickHitCorrectBasket called");
                        raise();
                        enlargeBonus();

                    },
                    onBrickHitWrongBasket: function () {
                        reduce();
                        resetBonus();
                    },
                    onBrickMissAllBaskets: function () { }
                };

               // alert("applyScorePolicyWithBonusEnabled called");
                that.currentScorePolicy.onBrickHitCorrectBasket();
            },

            applyScorePolicyWithBonusDisabled: function (scorePerQuestion) {
                currentScorePolicy = {
                    onBrickHitCorrectBasket: function () {
                        raise(scorePerQuestion); 
                    },
                    onBrickHitWrongBasket: function () {
                        reduce(scorePerQuestion);
                    },
                    onBrickMissAllBaskets: function () { }
                };
            },

            onBrickHitCorrectBasket: currentScorePolicy.onBrickHitCorrectBasket,
            onBrickHitWrongBasket: currentScorePolicy.onBrickHitWrongBasket,
            onBrickMissAllBaskets: currentScorePolicy.onBrickMissAllBaskets

        }

    })();

It's a score object for my game when the scoring policy may change during a game. The Score object expose two methods: applyScorePolicyWithBonusEnabled and applyScorePolicyWithBonusDisabled, thier goal is to alter the currentScorePolicy field.

Now, when I start my app I initialize Score and call applyScorePolicyWithBonusEnabled. Later on I call Score.onBrickHitCorrectBasket expecting that ScorePolicyWithBonus.onBrickHitCorrectBasket will execute, but in fact what is running is the original stub currentScorePolicy.onBrickHitCorrectBasket is called. I can tell by the alerts calls I planted there.

What's wrong? why does the call applyScorePolicyWithBonusEnabled() did not assigned the new object to currentScorePolicy?

4

0 回答 0