一,this的概念
任何函数本质上都是通过某个对象来调用的,如果没有直接指定(那么就是window)
所有函数内部都有一个变量this
它的值是调用函数的当前对象
二,this的指向
- 以函数形式 直接调用时,this指向window
- 以方法的形式调用时,this指向调用方法的对象,谁调用就指向谁,
- 以构造函数的形式调用时,this指向新创建的对象
- 以call和apply调用时,this指向其指定的首参对象
function Person(color){
console.log(this);
this.color=color;
this.getColor=function(){
console.log(this);
return this.color;
};
this.setColor=function(color){
console.log(this);
this.color=color;
};
}
Person("red"); //this指向window
var p=new Person("yello"); //this指向P
p.getColor(); // this指向p
var obj={};
p.setColor.call(obj,"red"); //this指向 obj(也就是obj调用setcolor)
var test=p.setColor;
test(); //this指向window
三,硬绑定的三个方法(this指向首参对象)
* call()/apply()是立即调用函数
* bind()是将函数返回,并没有调用,想要立即执行还需要加一个()