在Javascript上实现Singleton

时间:2012-11-12 13:24:24

标签: javascript

  

可能重复:
  Simplest/Cleanest way to implement singleton in JavaScript?

这是一个试图实现单例对象的代码片段。

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

        }

    })();

当比赛期间评分政策可能发生变化时,这是我游戏的得分对象。 Score对象公开了两个方法:applyScorePolicyWithBonusEnabledapplyScorePolicyWithBonusDisabled,其目标是更改currentScorePolicy字段。

现在,当我启动应用时,我会初始化分数并致电applyScorePolicyWithBonusEnabled。 后来我打电话给Score.onBrickHitCorrectBasket,期望ScorePolicyWithBonus.onBrickHitCorrectBasket将执行,但实际上正在运行的是调用原始存根currentScorePolicy.onBrickHitCorrectBasket。我可以通过我在那里种植的提醒电话告诉我们。

怎么了?为什么调用applyScorePolicyWithBonusEnabled()没有将新对象分配给currentScorePolicy

0 个答案:

没有答案