Javascript 带私有/公共的单例对象:公共函数依赖性问题

Javascript 带私有/公共的单例对象:公共函数依赖性问题,javascript,oop,Javascript,Oop,我只是在学习JavaScript,所以我制作了一个小规模的玩具应用程序来练习使用它,因为JavaScript中的OOP与我的经验中的经典语言非常不同。我决定把引擎做成一个带有一些封装的单体 我想问的是,如果两个公共职能以某种方式相互依赖,有没有更好的方式来实现这种模式?我之所以想问这个问题,是因为我正在使用对象文字实现公共接口,但不幸的是,这会导致函数表达式彼此不了解 或者,我应该完全放弃这个特定的模式,以不同的方式实现这个对象吗 代码如下: function PKMNType_Engine()

我只是在学习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;
        }
    };
}

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

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;
        }
    };
}