Function.prototype.method = function (name, func) {
this.prototype[name] = func;
return this;
};
从克罗克福德的好零件中偷走了。当代码返回'this'时,在这种情况下'this'引用是什么?
当我在js代码中看到'this'时,我总是问自己这是因为我知道js是时髦的,带有这个词(即'this'实际上引用了全局变量,当它在嵌套函数中使用时)
答案 0 :(得分:2)
在扩展Function.prototype
时,this
将引用一个函数实例。
示例:
function foo() {};
foo.method(); // `this` refers to foo
有四种不同的调用函数的方法,它们决定this
引用的内容。 MDN有一个good article。
简而言之:
window
)obj.method()
,this
引用obj
)(我们在您的示例中就是这种情况)new
关键字:一个空对象,继承自函数原型call
/ apply
:无论你作为第一个参数传递什么答案 1 :(得分:1)
在此上下文中,this
是对Function
实例的引用。
答案 2 :(得分:1)
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!