js this指向和call apply bind方法

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á)


?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容