开发者

What is 'this' referencing when it is inside a prototype? [duplicate]

开发者 https://www.devze.com 2023-04-04 15:08 出处:网络
This question already has answers here: What does "return this" do within a javascript function?
This question already has answers here: What does "return this" do within a javascript function? (4 answers) Closed 6 years ago.
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 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


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!
0

精彩评论

暂无评论...
验证码 换一张
取 消