Function.prototype.apply.call 理解分析

Function.prototype.apply.call 理解分析

首先需要了解apply,call的基本用法,其目的是改變調(diào)用方法中的this指向,將其指向?yàn)閭魅氲膶?duì)象,改變this的指向,兩種方法接收參數(shù)的方式不同。

代碼:console.log

var console = window.console || {log: function () {}};   
var log = console.log;  
console.log = function(tips,message){   
   Function.prototype.apply.call(log, console, arguments);   
   //Function.prototype.call.call(log, console, arguments);  
   //Function.prototype.call.apply(log, [console, arguments]);   
    
 //傳統(tǒng)方式  
 //var args=[].slice.call(arguments);  
 //log.apply(console,args);  
}  

執(zhí)行結(jié)果:

console.log("測(cè)試","This is test");  
測(cè)試 This is test  

分析:

該怎么理解Function.prototype.apply.call(log,console,arguments);呢

首先可以將Function.prototype.apply看成一個(gè)整體-->FunctionApply

FunctionApply.call(log,console,arguments);

那么將此句翻譯一下

log.FunctionApply(console,arguments);

然后再翻譯一下,你就懂了吧,就是一個(gè)普通方法調(diào)用了

console.log(arguments);

發(fā)散思維:

Function.prototype.call.apply(log,[console.arguments]);

FunctionCall.apply(log,[console,arguments]);  
log.FunctionCall(console,arguments);  
console.log(arguments);  

小tips:

 Function.prototype.apply.call  等同于Function.prototype.call.call
 Function.prototype.call.apply  等同于 Function.prototype.apply.apply

例子:

function testA(a){  
    console.log('aaaa',a);  
}  
Function.prototype.apply.call(testA,window,['Mike']);  
//Function.prototype.call.call(testA,window,['Mike']);  
//testA.apply(window,['Mike']);  
//window.testA('Mike');  
//Function.prototype.apply.apply(testA,[window,['Mike']]);  
//Function.prototype.call.apply(testA,[window,['Mike']]);  

以上執(zhí)行結(jié)果都一樣

為:aaaa Mike

總結(jié)使用用法:

XXX可以是call或者是apply,child一定是parent可指向的對(duì)象

Function.prototype.XXX.call(child,parent,arguments||array);

Function.prototype.XXX.apply(child,[parent,arguments||array]);

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

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

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