2011-10-01 18 views
1

在JavaScript中處理以下情況的最佳方法是什麼?當方法依賴於另一種方法

我有三個方法(m1m2m3),最後一個(m3)取決於與其他兩(m1m2)的結果。

以這種方式工作,但我很想知道在這種情況下是否有更好的方法來編寫代碼,特別是對於將要閱讀代碼的未來開發人員。

var O = function() { 
    this.p = 0; 
} 

O.prototype.makesomething = function() { 
    var that = this; 
    that.m1(); 
    that.m2(); 
    that.m3(); 
} 

O.prototype.m1 = function() {O.p++}; // it changes the value O.p 
O.prototype.m2 = function() {O.p++}; // it changes the value O.p 
O.prototype.m3 = function() {return O.p}; // m3 depends by m1, m2 because it needs to get the update value of O.p 
+0

請問你總是在這個特定的順序調用這三個函數?或者你可以以不同的順序打電話給m1,m2和m3,或者一次不打三個電話? – Michael

+0

我重寫了代碼;順便說一下,如果我讀了下面的代碼,我可以假設m1,m2和m3是獨立的;但是實際上m3不是,所以我如何能夠明確它? – antonjs

+0

從你提供的代碼中可以看出,O.p究竟是如何變化的?介意提供最小的工作代碼示例,預期的行爲,以及出錯的地方。 –

回答

1

首先,我不知道是肯定的,但把this.p = 0O無厘頭結合O.p。當涉及到實例時,您可能的意思是this.p,內部爲m3

無論如何,如果你正在尋找可讀性,你可以做一些簡單但慣用的功能,如:http://jsfiddle.net/ZvprZ/1/

var O = function() { 
    this.p = 0; 
} 

O.prototype.makesomething = function() { 
    var that = this; 

    var result = when(that.m1(), that.m2()) 
       .then(that.m3()); 

    return result; 
} 

O.prototype.m1 = function() {this.p++}; 
O.prototype.m2 = function() {this.p++}; 
O.prototype.m3 = function() {return this.p}; 

when/then可以是相當直接的,因爲它沒有做任何事情比使其更具可讀性:

(function(window) { 
    var when, then, o; 

    when = function() { 
     return o; // just return the object so that you can chain with .then, 
        // the functions have been executed already before executing 
        // .when 
    }; 

    then = function(a) { 
     return a; // return the result of the first function, which has been 
        // executed already (the result is passed) 
    }; 

    o = { when: when, 
      then: then }; 

    window.when = when; // expose 
    window.then = then; 
})(window);