In JavaScript, Functions are first class objects. When you define a function, this is the constructor for this 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
new gmap ();
To test the variable, you created a new object that "inherits" all the properties and methods from the constructor (class) gmap (). If you run the snippet above, you will see a warning for โaddโ and โdeleteโ.
In the above examples, โthisโ refers to a window object, unless you wrap functions in another function or object.
It's hard for me to understand the chain, at least for me, but as soon as I understood it, I realized how powerful a tool can be.
Lark Jul 08 '09 at 18:22 2009-07-08 18:22
source share