Search code examples
javascriptchainingmethod-chaining

Javascript chaining and variable substitute


I am trying to get javascript chaining to work using variable substitution. Not able to get it work. Help appreciated.

var Class = function() {

 this.one = function() {
   alert('one');        
   return this;
 }

 this.two = function() {
   alert('two');
   return this;
 }

 if (this instanceof Class) {
    return this.Class;
 } else {
    return new Class();
 }

}

var test = new Class();
// this works
test.one().two();

var func = '.one().two()';
// want to make this work
test[func];

Solution

  • Highly not recommended. You might want to try an array instead:

    var funcs = ['one','two'];
    for(var i = 0; i < funcs.length; i++) {
      test[funcs[i]]();
    }
    

    you can then wrap this into a little function:

    function callChain(obj, funcs)
    {
      for(var i = 0; i < funcs.length; i++) {
        obj[funcs[i]]();
      }
      return obj;
    }
    

    Edit: If your chain is stored as a string: .one().two(), you can use the split & string functions to generate the array dynamically.