1

In my ongoing saga to understand more about Object Oriented Javascript - I came across a question about creating a class to respond to the following API:

var foo = new bar().delay(750).start().then(onComplete);

var bar = function() {
    this.delay(function(per) {
      //...
    };
}

Can someone with more experience than me please describe how to create class that would respond to this? I have never seen chaining like this and can't find any information online :(

1

2 Answers 2

4

This chaining is accomplished by returning this in your functions :

this.delay = function(per) {
  //...
  return this;
};

If you want to stick to first line code, then your constructor should be named bar :

var bar = function() {
    this.delay = function(per) {
      //...
      return this;
    };
    this.start = function() {
      ...
      return this;
    };
}

See demonstration (open the console)

Sign up to request clarification or add additional context in comments.

Comments

1

The secret to method chaining is to return this from each method that you want to be able to chain with. That allows the next method to be this.method() automatically. Your definition of the bar object would look something like this shell:

function bar() {
    // bar initialization code here
}

bar.prototype = {
    delay: function(amt) {
        // delay code here
        return(this);
    },
    start: function() {
        // start code here
        return(this);
    },
    then: function(fn) {
        // then code here
        fn();
        return(this);
    }
};


var foo = new bar().delay(750).start().then(onComplete);

In your example, new bar() is executed and it returns a pointer to the new bar object. Using that new object pointer, the .delay(750) method is called on that object. That method then also returns the object so the .start() method is called on the return value from .delay(750) which is still the same object and so on...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.