第一种:函数直接调用执行的模式
function add(a,b){
console.log(this);
return a+b;
}
add(,)
//this===window 这里的this指向是window的
第二种:对象方法的调用模式
var people={
name:'wang',
sex:'男',
eat:function(){
console.log(this);
}
}
people.eat();
//this===对象,对象方法调用时,this指向被调用者
第三种:构造器的调用模式
function People(){
this.eat=function(){
console.log(this);
}
}
var wang=new People();
wang.eat();
//对象调用自己的方法,this===wang,谁new的this指向谁
第四种:call和apply调用模式
call方法有多个参数,第一个是要绑定给this的值,后面跟是若干。
apply方法有两个参数,第一个是要绑定给this的值,第二个是一个参数数组可以放若干。
function change(a,b){
this.detial=a*b;
console.log(this);
}
var p={};
change.call(p,,);//此处的this===p
console.log(p.detial);
var q=[];
change.call(q,,)//this===q
console.log(q.detial); //apply和call一样的用法,只不过apply第二个参数用数组进行传递
var arr=[];
change.apply(arr,[,]);//this===arr
console.log(arr.detial); var str={};
change.apply(str,[,]);//this===str
console.log(str.detial);