2012-01-05 59 views
2

我已經搜索並閱讀了幾個小時,但仍無法理解用於創建具有不同方法選擇的新對象的基本設計模式(具有相同名稱),其取決於其中一個參數。這裏有一些代碼來解釋我正在嘗試做什麼。 歡迎提供所有建議和替代方法。我希望有人能解放我,形成這種無知的雲。 感謝根據對象創建期間的參數選擇對象所具有的方法集合 - JavaScript

function BaseConstructor(whichMethods) { 
    if (whichMethods==='a') { 
     // do something to incorporate methodSetA 
    } 
    else if (whichMethods==='b') { 
     // do something to incorporate methodSetB 
    } 

    this.init(); 
}; 

var methodSetA = { 
    init: function() { 
     // do initialisation A way 
    }, 
    speak: function() { 
     alert('i speak AAA way') 
    } 
}; 

var methodSetB = { 
    init: function() { 
     // do initialisation B way 
    }, 
    speak: function(){ 
     alert('i got BBB all the way') 
    } 
}; 

thing = new BaseConstructor('b'); 
// b is an instance of BaseConstructor and has done the bWay init() function 

thing.speak() // return alert 'i got BBB all the way' 

回答

0

您可以使用工廠函數(,爲您創建合適的對象常規的函數)做這樣的:

function BaseConstructor(whichMethods) { 
    var elem; 
    if (whichMethods==='a') { 
     elem = new MethodSetA(); 
    } else if (whichMethods==='b') { 
     elem = new MethodSetB(); 
    } else { 
     // figure out what to do here if whichMethods is neither of the previous options 
    } 

    elem.init(); 
    return(elem); 
}; 

並調用它作爲一個普通函數調用:

var thing = BaseConstructor('b'); 
thing.speak(); 

注意:newBaseConstructor()沒有任何用處,因爲它是常規函數調用。

+0

明白了,感謝您的及時回覆!工廠設計模式 - 我今天肯定已經閱讀了5次,並且有點認爲這是我需要的,但總是在無關的細節中分散注意力。再次感謝@ jfriend00 – johowie 2012-01-05 03:02:50

0

好了,使用 「方法設置」,你可以遍歷並複製到thishere's a demo)做你的方式:

function copy(source, destination) { 
    for(var x in source) { 
     if(source.hasOwnProperty(x)) { 
      destination[x] = source[x]; 
     } 
    } 
} 

function BaseConstructor(whichMethods) { 
    if(whichMethods === 'a') { 
     copy(methodSetA, this); 
    } else if(whichMethods === 'b') { 
     copy(methodSetB, this); 
    } 

    this.init(); 
} 

就個人而言,雖然,我更願意分配直接到this

+0

謝謝你的建議,並找到一個辦法做到這一點「我的路」,我會從你的代碼中學習。再次感謝@ minitech – johowie 2012-01-05 03:05:38

0

您正在尋找工廠模式。 例子:

function objectFactory(whichMethods) { 
     if (whichMethods==='a') { 
      return new objectSetA(); 
     } 
     else if (whichMethods==='b') { 
      return new objectSetB() 
     } 
    }; 
    function objectSetA() { 
     this.init = function() { 
     // do initialisation A way 
     }, 
     this.speak = function() { 
      alert('i speak AAA way') 
     } 
    }; 

    function objectSetB() { 
     this.init = function() { 
     // do initialisation B way 
     }, 
     this.speak = function(){ 
      alert('i got BBB all the way') 
     } 
    }; 
    var thing = objectFactory('b'); 
    thing.speak(); 
+0

感謝您的及時和明確的答覆,的確我需要一個工廠! @petar – johowie 2012-01-05 03:07:55

+0

說方法應該在各自的構造器的原型上。 – RobG 2012-01-05 04:01:51

+0

@RobG在原型上放置speak()方法是有意義的。你有沒有理由不在原型上使用init()方法? – johowie 2012-01-05 06:20:11