this指向
關(guān)于this指向,我們可以理解為哪個對象調(diào)用函數(shù),函數(shù)里面的this指向哪個對象。
??????function?a( ){??????????
??????????????console.log(this) ;//this(window)
?????}????????
? ? ? a( );
????function b( )?{?
???????????console.log(this);//this(b函數(shù)對象)
???????}?
? ? ? ?new? ?b( );
總結(jié)一下就是函數(shù)a為普通函數(shù)對象,這種函數(shù)對象執(zhí)行的this是window,函數(shù)b為構(gòu)造函數(shù)對象,它的this是調(diào)用的函數(shù)對象
call?apply??bind的用法
????????var?obj?=?{
????????????name:'張三',??
? ? ? ? ? ? say:function(str,str2){
????????????????console.log(this.name+'? '+str+'? '+str2)??//?李四 hello world? ? ? ? ?
?????????}???????
?}
???var?f?=??obj.say.call({name:'李四'},'hello','world');? ? ??
//? ?call() 可以調(diào)用函數(shù),也可以改變函數(shù)this的指向
? ? ? ? var obj={
? ? ? ? ? ? name:'張三',
? ? ? ? ? ? say:function(str,str2){
? ? ? ? ? ? ? ? ? ? conlose.log(this.name+' '+str+' 'str2)? ?//? 李四? hello world? ? }
}
? ? var? f=??obj.say.bind({name:'李四'},'hello','world');
? ? f(? )
//bind方法使用的時候需要再次調(diào)用
? ? ? ? var obj={
? ? ? ? ? ? name:'張三',
? ? ? ? ? ? say:function(str,str2){
? ? ? ? ? ? ? ? ? ? conlose.log(this.name+' '+str+' 'str2)? ?//? 李四? hello world
? ? }
}
? ? var? f=??obj.say.apply({name:'李四'},['hello','world']);
//使用apply方法改變this指向時參數(shù)需要以數(shù)組形式表達(dá)