使用apply调用函数

题目描述

实现函数 callIt,调用之后满足如下条件
1、返回的结果为调用 fn 之后的结果
2、fn 的调用参数为 callIt 的第一个参数之后的全部参数

代码

 1 /*因为arguments并非真正的数组,因此要获得callIt的第一个参数之后的所有参数,
 2 不能直接使用slice方法截取,需要先将arguments转换为真正的数组才行*/
 3 //方法一:使用slice方法:var args = Array.prototype.slice.call(arguments);
 4 function callIt(fn) {
 5      //将arguments转化为数组后,截取第一个元素之后的所有元素
 6      var args = Array.prototype.slice.call(arguments,1);
 7      //或return fn.apply(null.args),因为给apply传递null,“”空字符串,默认都是this
 8      return fn.apply(this,args);
 9 }
10 
11 //方法二:for循环
12 function callIt(fn) {
13     var args = new Array();
14     for(var i=1; i<arguments.length; i++){
15         args[i-1] = arguments[i];
16     }
17     return fn.apply(this,args);
18 }

来源:牛客网

 

原文地址:https://www.cnblogs.com/daheiylx/p/8900101.html