组合函数的通用实现

组合函数:当某个数据每次调用完一个函数又需要调另一个函数时,可以把这两个函数组合起来更加方便,组合后可以自动依次调用。

举个简单的例子:普通的组合函数

 1 function hyCompose(t1, t2) {
 2     return function compose(t3) {
 3         return t2(t1(t3))
 4     }
 5 
 6 }
 7 
 8 function add(x) {
 9     return x + 2
10 }
11 
12 function power(y) {
13     return y ** 2
14 }
15 var bar = hyCompose(add, power)
16 console.log(bar(8));

 

这样就实现了简单的把两个函数组合到hyCompose函数里面

思考:当需要组合的函数有很多个呢,如此同时参数也有很多个呢?我们就可以写出通用组合函数写法

思路:传入多个函数,用...fns来接收 然后变量判断typeof fns[i]的类型是不是函数 然后先var一个结果是第一个函数的值,最后再while来使用每个函数,特别注意apply接收的参数必须是数组类型,必要的时候可以使用call

 1 function hyCompose(...fns) {
 2     var length = fns.length
 3     for (var i = 0; i < length; i++) {
 4         if (typeof fns[i] !== 'function') {
 5             throw new TypeError("你需要传入一个函数")
 6         }
 7     }
 8 
 9     function compose(...args) {
10         var index = 0
11         var result = length ? fns[index].apply(this, args) : args
12         while (++index < length) {
13             // result = fns[index].apply(this, [result])
14             result = fns[index].call(this, result)
15         }
16         return result
17     }
18     return compose
19 }
20 
21 function m(x, z) {
22     return x + z + 2
23 }
24 
25 function n(y) {
26     return y ** 2
27 }
28 var bar = hyCompose(m, n)
29 console.log(bar(8, 2));
30 console.log(12 * 12);

两个输出的结果是一样的,实现成功!

上图第6行代码 是指抛出一个异常 使用throw new ---Error()

注意:callapply可以用来重新定义函数的执行环境,也就是this的指向;callapply都是为了改变某个函数运行时的上下文而存在的,换句话说,就是为了改变函数体内部this的指向。

 
posted @ 2022-03-16 19:21  沁霓  阅读(102)  评论(0)    收藏  举报