Singleton对象w / Private / Public:公共函数依赖问题

时间:2013-08-17 23:50:09

标签: javascript oop

我正在学习JavaScript,因此我正在制作一个小型玩具应用程序以便练习使用它,因为根据我的经验,JavaScript中的OOP与经典语言非常不同。我决定用一些封装使发动机成为单体。

我想问的是,如果两个公共函数以某种方式依赖,是否有更好的方法来实现这种模式?我想问这个是因为我使用对象文字来实现公共接口,但不幸的是,这导致函数表达式不能彼此了解。

或者,我应该完全放弃这个特定模式并以不同的方式实现对象吗?

以下是代码:

function PKMNType_Engine(){
    "use strict";

    var effectivenessChart = 0;
    var typeNumbers = {
        none: 0,
        normal: 1,
        fighting: 2,
        flying: 3,
        poison: 4,
        ground: 5,
        rock: 6,
        bug: 7,
        ghost: 8,
        steel: 9,
        fire: 10,
        water: 11,
        grass: 12,
        electric: 13,
        psychic: 14,
        ice: 15,
        dragon: 16,
        dark: 17,
        fairy: 18
    };

    return {

        /**
         *Looks up the effectiveness relationship between two types.
         *
         *@param {string} defenseType 
         *@param {string} offenseType
         */
        PKMNTypes_getEffectivness: function(defenseType, offenseType){
            return 1;
        }

        /**
         *Calculates the effectiveness of an attack type against a Pokemon
         *
         *@param {string} type1 The first type of the defending Pokemon.
         *@param {string} type2 The second type of the defending Pokemon.
         *@param {string} offensiveType The type of the attack to be received.
         *@return {number} The effectiveness of the attack
         */
        PKMNTypes_getMatchup: function(type1, type2, offensiveType){
            var output = PKMNTypes_getEffectivness(type1, offensiveType) * PKMNTypes_getEffectivness(type2, offensiveType);
            return output;
        }
    };
}

1 个答案:

答案 0 :(得分:2)

您可以简单地在构造函数内部(或旁边)定义函数,只需将它们“附加”到新实例即可。这样,函数可以根据需要自由引用:

function PKMNType_Engine(){
    "use strict";

    function getEffectiveness(defenseType, offenseType){
        return 1;
    }

    return {
        PKMNTypes_getEffectivness: getEffectiveness,

        PKMNTypes_getMatchup: function(type1, type2, offensiveType){
            var output = getEffectiveness(type1, offensiveType) *
                         getEffectiveness(type2, offensiveType);
            return output;
        }
    };
}