美文网首页
Function.prototype.apply.call 理解

Function.prototype.apply.call 理解

作者: 如果俞天阳会飞 | 来源:发表于2019-08-27 15:53 被阅读0次

Function.prototype.apply.call 理解分析

首先需要了解apply,call的基本用法,其目的是改变调用方法中的this指向,将其指向为传入的对象,改变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]);

相关文章

  • Function.prototype.apply.call 理解

    Function.prototype.apply.call 理解分析 首先需要了解apply,call的基本用法,...

  • 理解!理解!!理解!!!

    1、如何理解MVC设计模式 MVC是一种架构模式,M表示MOdel,V表示视图View,C表示控制器Control...

  • 理解“理解”

    教育不是灌输而是揭示 教育就是向智者揭示智慧,对愚者掩盖无知。——安布罗斯 比尔斯 我们的课堂教学要做的是设计表现...

  • 理解理解,再理解

    【今日悦读】 1214-潇潇 书名:财富自由之路 作者:李笑来 篇目:10~12节 收获: 1,人生三大坑 莫名其...

  • 理解不被理解

    一个人的坐在电脑前发呆,不知道搞什么,闭上眼睛,感觉自己很孤独。这种是内心的那种,很不是滋味,不知道什么时候自己才...

  • 理解你的理解理顺理解

    理解你的理解理顺你的理解 生活中因为缺乏准确具体到位的沟通和具体的实施方向和可落地的方式,因为信息传达...

  • 理解不理解

    对于更多人而言,或许他们更看重的是对与错,是与非。这种执念而且经常让一些人变了味,甚至格格不入。 而对于个人而言,...

  • 理解不曾理解的

    上学时从来没把容貌当成大事儿,只是希望脸上的痘痘能少点,至于什么皮肤白、毛孔粗大、黑眼圈、肤色暗淡、脸型、眉形、眼...

  • 理解与被理解

    凡事都设身处地为别人着想,自己不愿做的事情也不强加给别人,理解的核心在于不自我。

  • 理解什么是理解

    《理解什么是理解》-花花 每个人都渴望被理解,希望被理解,不被理解是一件很痛苦的事情。 小朋友不理解妈妈为对自己反...

网友评论

      本文标题:Function.prototype.apply.call 理解

      本文链接:https://www.haomeiwen.com/subject/ogmeectx.html