Function.prototype.apply.call

我们先从一道简单的题目开始,前几天在git上看到的:

定义log方法,它可以代理console.log的方法。
log(1,2,3)  =>  1 2 3

通常,你的答案会是这样的:

function log(){
    var args = Array.prototype.slice.call(arguments);       
    console.log.apply(console, args); 
};

直到有一天,你看到一个非常高大上的答案:

function log(){
  Function.prototype.apply.call(console.log,console, arguments);
};


Function.prototype.apply.call。。。。这是什么鬼???

好吧,那你一定认识
Function.prototype.apply吧,我们将它缓存一下:
var core_apply=Function.prototype.apply;
core_apply.call(console.log,console, arguments)我们可以将它分解下

  1、调用core_apply方法,console.log是core_apply这个方法的this指向,console,arguments是要传给core_apply这个方法的参数。

  也就是说,它其实等同于  

console.log.core_aply(console,arguments);

=》

调用console.log()方法,this指向console,传入的参数为arguments.



原文地址:https://www.cnblogs.com/qianlegeqian/p/4040183.html