Function.prototype.apply.call的总结

 

网上看到一段代码,哎,觉得挺不错,然后来分析一下,

首先需要了解apply,call的基本用法,其目的是改变调用方法中的this指向,将其指向为传入的对象

 

代码: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]); 
  
 //传统方式
 //var args=[].slice.call(arguments);
 //log.apply(console,args);
}

 

 

执行结果:

 

console.log("测试","This is test");

 

测试 This is test

 

分析:

 

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

      首先可以将Function.prototype.apply看成一个整体-->FunctionApply

       FunctionApply.call(log,console,arguments);

       那么将此句翻译一下

       log.FunctionApply(console,arguments);

       然后再翻译一下,你就懂了吧,就是一个普通方法调用了

       console.log(arguments);

 

发散思维:

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']]);

 

以上执行结果都一样

    为:aaaa Mike

 

总结使用用法:

    XXX可以是call或者是apply,child一定是parent可指向的对象

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

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值