链式调用
大家都知道链式调用能够让代码更简洁易读,一般用于批量数据的多次复杂处理。
关于它的实现原理一般有两种方式:
1.构造函数的实例方法或原型方法执行完后 return this
function Person() {
this.run=function () {
console.log('run')
return this // 返回调用run方法的对象自身
}
this.stop=function () {
console.log('stop')
return this
}
}
const xx = new Person()
如果你想先调用run,再调用stop,不用写成下面这样
xx.run()
xx.stop()
而是可以写成
xx.run().stop()
2.普通函数执行完后 return 函数自身
最简单的例子:
let val = 1
const fun = function () {
console.log(val)
val++
return fun
}
console.log(fun()()()()()())
// 1
// 2
// 3
// 4
// 5
// 6
看到这个函数之后有没有觉得很像递归函数
递归函数是通过调用自身实现的一种迭代方式,必须写函数退出条件。
链式调用函数也是调用自身,更像是一种可控的递归函数,写多少个(),它就执行多少次。
这么一说,链式调用函数更更像是一种迭代器函数。
看下面的例子
function iterate(arr) {
let index = 0
const fun = function () {
arr[index] = arr[index]*2 //对参数arr进行迭代处理
index++
return fun
}
fun.stop = function () { //中止迭代的静态方法
return arr
}
return fun
}
console.log(iterate([1,2,3])()()().stop()) // [2, 4, 6]
上面的代码实现了一个跟for循环类似的功能,可以对数组执行迭代操作。
当然靠写一堆()去迭代,代码就没法读了,还要去查数,看看到底迭代了多少次。。。
所以链式调用可以理解为,明确知道要迭代多少次,并且次数不会太多时,使用起来就会好看很多。
总结
当你读一些源码时看到 return this
或者 return 函数自身 的时候。
不要慌,通常就是个链式调用。
欢迎来我的b站空间逛逛
https://space.bilibili.com/395672451