How does basic object/function chaining work in javascript?

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.

Leave a Comment