2013-08-17 66 views
0

我剛剛學習JavaScript,因此我正在製作一個小型玩具應用程序以便練習使用它,因爲JavaScript中的OOP與我的經典語言經驗。我決定用一些封裝將引擎變成單身。Singleton object w/Private/Public:公共函數依賴問題

我想問的是,如果兩個公共函數依賴於某種方式,是否有更好的方法來實現這種模式?我想問這個問題是因爲我正在使用對象字面值來實現公共接口,但不幸的是這會導致函數表達式不知道對方。或者,我應該完全拋棄這種特定的模式並以不同的方式實現對象嗎?

下面是代碼:

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

回答

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