Secondary encapsulation function [JavaScript]

1. Use apply to call a function

Title description

Implement the function callIt, meet the following conditions after calling
1. The returned result is the result after calling fn
2. The calling parameter of fn is all the parameters after the first parameter of callIt
Example 1
Input

No
output

no

Because arguments are not real arrays, to get all the parameters after the first parameter of callIt, you cannot directly use the slice method to intercept, you need to convert the arguments to a real array first. There are two common methods, one is to use the slice method: var args = Array. Prototype. Slice. Call (arguments ); the other is to loop through and fill in the new array one by one. After obtaining the args, you can call apply to execute the passed function parameters.
code show as below:

function callIt(fn) {
    
    
    //将arguments转化为数组后,截取第一个元素之后的所有元素
    var args = Array.prototype.slice.call(arguments,1);
    //调用fn
    var result = fn.apply(null,args);
    return result;
}

Two. Secondary packaging function

Implement the function partialUsingArguments, and meet the following conditions after calling:
1. Return a function result
2. After calling result, the returned result is consistent with the result of calling the function fn
3. The calling parameters of fn are all parameters after the first parameter of partialUsingArguments and Call parameters of result
Example 1

Input
none

Output
none

This question is a little more complicated than the first question. Arguments cannot be directly intercepted by the slice method. They need to be converted to an array first. var args = Array.prototype.slice.call(arguments); the concat method can be used to merge the parameters, and the arguments need to be first. Convert to an array to merge using concat. Most use apply to execute the passed function.
code show as below:

function partialUsingArguments(fn) {
    
    
     //先获取p函数第一个参数之后的全部参数
     var args = Array.prototype.slice.call(arguments,1);
     //声明result函数
     var result = function(){
    
    
         //使用concat合并两个或多个数组中的元素
         return fn.apply(null, args.concat([].slice.call(arguments)));
     }
     return result;
 }

Guess you like

Origin blog.csdn.net/weixin_42345596/article/details/105060469