How does basic object/function chaining work in javascript?

Geuis picture Geuis · Jul 8, 2009 · Viewed 29.1k times · Source

I'm trying to get the principles of doing jQuery-style function chaining straight in my head. By this I mean:

var e = f1('test').f2().f3();

I have gotten one example to work, while another doesn't. I'll post those below. I always want to learn the first principle fundamentals of how something works so that I can build on top of it. Up to now, I've only had a cursory and loose understanding of how chaining works and I'm running into bugs that I can't troubleshoot intelligently.

What I know:

  1. Functions have to return themselves, aka "return this;"
  2. Chainable functions must reside in a parent function, aka in jQuery, .css() is a sub method of jQuery(), hence jQuery().css();
  3. The parent function should either return itself or a new instance of itself.

This example worked:

var one = function(num){
    this.oldnum = num;

    this.add = function(){
        this.oldnum++;
        return this;
    }

    if(this instanceof one){
        return this.one;    
    }else{
        return new one(num);    
    }
}
var test = one(1).add().add();

But this one doesn't:

var gmap = function(){

    this.add = function(){
        alert('add');

        return this;    
    }   

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

}
var test = gmap.add();

Answer

Lark picture Lark · Jul 8, 2009

In JavaScript Functions are first class Objects. When you define a function, it is the constructor for that function object. In other words:

var gmap = function() {
    this.add = function() {
        alert('add');
    return this;
    }

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

    if (this instanceof gmap) {
        return this.gmap;
    } else {
        return new gmap();
    }
}
var test = new gmap();
test.add().del();

By assigning the

new gmap();
to the variable test you have now constructed a new object that "inherits" all the properties and methods from the gmap() constructor (class). If you run the snippet above you will see an alert for "add" and "delete".

In your examples above, the "this" refers to the window object, unless you wrap the functions in another function or object.

Chaining is difficult for me to understand at first, at least it was for me, but once I understood it, I realized how powerful of a tool it can be.