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
, this
will refer to a function instance.
Example:
function foo() {};
foo.method(); // `this` refers to foo
There are like four different ways of calling functions, which determine what this
refers to. MDN has a good article about it.
In short:
- Simple function call: Global object (
window
in browsers) - Object method: The object (i.e.
obj.method()
,this
referencesobj
) (that's the case we have in your example) - Using the
new
keyword: An empty object, inheriting from the functions prototype call
/apply
: Whatever you pass as first argument
In this context, this
is a reference to the Function
Instance.
this
refers to the constructor Function that calls it's method
method. So for example you can do this:
function Car(color){
this.color = color || 'blue';
}
Car.method('showcolor',function(){return this.color;});
//^Car is a constructor function, so 'this' in 'method' refers to Car here
var redcar = new Car('red'), yellowcar = new Car('yellow');
alert(redcar.showcolor()); //=> red
alert(yellowcar.showcolor()); //=> ... you guessed it!
精彩评论