javascriptc#jqueryfunctionchaining

JavaScript chaining function / function extends using IIFE expression


I've been looking for a way of extending a function in a straightforward way, like in C# extension method.

I've tried the following statement which I have found in this article Method Chaining in JavaScript and which works fine.

var FOO = function(){
     this.whateverFunc = function(){
         console.log("whatever func");
     }
};
FOO.prototype.first = function(){
     console.log("first func");   
     return this;  
};
FOO.prototype.second = function(){
     console.log("second func");   
     return this;  
};

Then I can chain it:

 var foo = new FOO();
 foo.first().second();
 //Output
 //first func
 //second func

BUT: My projects has the following "pattern":

var FOO = (function(){
    var foo{
        firstFunc: function(){
            //implement
        },
        secondFunc: function(){
            //implement
        },
    }
    return foo;
}());

It doesn't work even if I don't use IIFE.

 var FOO = function() { var foo{}; return foo; };

Is there a way to use chaining function within that pattern? How could I accomplish this(if this is possible!):

FOO.first().second();

Thanks.


Solution

  • The only issue with the code following

    BUT: My projects has the following "pattern":

    is missing = at foo declaration.

    If IIFE uses arrow function the invoking parentheses should be last part of IIFE, instead of within outer parentheses.

    var FOO = (function() {
      var foo = {
        firstFunc: function() {
          //implement
          console.log(1);
          return this
        },
        secondFunc: function() {
          //implement
          console.log(2);
          return this
        }
      }
      return foo;
    })();
    
    FOO.firstFunc().secondFunc()