Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
Stolen from Crockford’s Good Parts. When the code returns ‘this’, what does ‘this’ reference in this case?
I always ask myself this when I see ‘this’ inside a js code because I know that js is funky with the word this (i.e. ‘this’ actually references the global variable when it is used inside a nested function)
As you are extending
Function.prototype,thiswill refer to a function instance.Example:
There are like four different ways of calling functions, which determine what
thisrefers to. MDN has a good article about it.In short:
windowin browsers)obj.method(),thisreferencesobj) (that’s the case we have in your example)newkeyword: An empty object, inheriting from the functions prototypecall/apply: Whatever you pass as first argument