2011-10-01 23 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);