Javascript四种调用模式中的this指向

第一种:函数直接调用执行的模式

function add(a,b){  
    console.log(this);   
    return a+b; 
}
add(1,2)
//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,4,5);//此处的this===p
console.log(p.detial);
var q=[];
change.call(q,5,10)//this===q
console.log(q.detial);

//apply和call一样的用法,只不过apply第二个参数用数组进行传递
var arr=[];
change.apply(arr,[10,10]);//this===arr
console.log(arr.detial);

var str={};
change.apply(str,[20,20]);//this===str
console.log(str.detial);
             

 

posted @ 2017-03-11 18:28  小兔额乖乖  阅读(156)  评论(0编辑  收藏  举报