Saxophlutist
Saxophlutist

Reputation: 291

Singleton object w/ Private/Public: Public function dependency problems

I am just learning JavaScript, so I am making a small-scale toy application in order to practice using it, since OOP in JavaScript is very different from Classic languages in my experience. I decided to make the engine a singleton with some encapsulation.

What I wanted to ask is, if two public functions are dependent somehow, is there a better way of doing this pattern? I wanted to ask this because I was implementing the public interface using an object literal, but unfortunately this causes the function expressions not to know about each other.

Or, should I abandon this specific pattern completely and implement the object a different way?

Here is the code:

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

Upvotes: 0

Views: 62

Answers (1)

Jon
Jon

Reputation: 437406

You can simply define the functions inside (or alongside) the constructor and just "attach" them to the new instance. This way the functions are free to refer to one another as required:

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

Upvotes: 2

Related Questions