antonjs
antonjs

Reputation: 14318

When a method depends on another method

What is the best way to deal with the following situation in JavaScript.

I have three methods (m1, m2, m3) and the last one (m3) depends from the results of the others two (m1, m2).

In this way it works, but I am curious to know if there is a better way to write the code in this situation, especially for future developers that will read the code.

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

Upvotes: 1

Views: 227

Answers (1)

pimvdb
pimvdb

Reputation: 154908

First, I don't know for sure, but putting this.p = 0 inside O does not make sense in combination with O.p. You probably mean this.p inside m3, when referring to the instance.

Anyway, if you are looking for readability, you could make some simple but idiomatic functions like this: 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};

The when/then can be rather straight-forward since it does not do anything than making it more readable:

(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);

Upvotes: 1

Related Questions