1
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)

denniss
  • 17,229
  • 26
  • 92
  • 141

3 Answers3

2

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 references obj) (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
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

In this context, this is a reference to the Function Instance.

evildead
  • 4,607
  • 4
  • 25
  • 49
1

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!
KooiInc
  • 119,216
  • 31
  • 141
  • 177