什么是'this'当它在原型中时引用

What is 'this' referencing when it is inside a prototype?

本文关键字:原型 引用 this 什么      更新时间:2023-09-26
Function.prototype.method = function (name, func) {
    this.prototype[name] = func;
    return this;
};

从Crockford的Good Parts偷来的。当代码返回'this'时,在这种情况下'this'引用是什么?

当我在js代码中看到"this"时,我总是问自己这个问题,因为我知道js中有"this"这个词。'this'在嵌套函数中使用时实际上引用全局变量)

在扩展Function.prototype时,this将引用函数实例。

的例子:

function foo() {};
foo.method(); // `this` refers to foo

有四种不同的函数调用方式,它们决定了this所指的是什么。MDN有一篇很好的文章。

简而言之:

  • 简单的函数调用:全局对象(window在浏览器)
  • 对象方法:对象(即obj.method(), this引用obj)(这就是我们在您的示例中的情况)
  • 使用new关键字:一个空对象,继承函数原型
  • call/apply:无论你传递的第一个参数

在此上下文中,this是对Function实例的引用。

this是指调用它的method方法的构造函数。例如,你可以这样写:

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!