链式调用在JavaScript很常见,比如jQuery、Promise和其它的插件等,都是使用的链式调用。链式调用可以让我们在进行连续操作时,写出更简洁的代码。
链式调用它允许你在单个对象上连续调用多个方法,每个方法的返回值都是调用它的那个对象本身(或者是另一个可以进行链式调用的对象)。这种编程风格可以使代码更加简洁和易读。
1,使用对象进行链式调用
let obj={
start(){
console.log("这是测试1")
return this
},
center(){
console.log("这是测试2")
return this
},
end(){
console.log("这是测试3")
return this
}
}
obj.start().center().end()
//这是测试1
//这是测试2
//这是测试3
1,使用函数进行链式调用
function Person(name,age) {
this.name=name
this.age=age
}
//在原型上添加方法
Person.prototype={
start(){
console.log("这是测试1")
return this
},
center(){
console.log("这是测试2")
return this
},
end(){
console.log("这是测试3")
return this
}
}
let P1=new Person("张三",18)
P1.start().center().end()
//这是测试1
//这是测试2
//这是测试3
3,类似jquery中的链式调用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>函数链式调用</title>
<style>
#doms{
width:100px;
height: 100px;
border: 1px solid red;
}
</style>
</head>
<body>
<div id="doms"></div>
<script>
function selectContent(selector) {
return{
el:document.querySelector(selector),
height:function(h){
this.el.style.height=h
return this
},
width:function(w){
this.el.style.width=w
console.log(this)
return this
}
}
}
let dom = selectContent("#doms")
//dom.height('220px')
dom.height('220px').width('220px')
</script>
</body>
</html>
4,遍历数组进行链式调用
function f1() {
console.log("f1")
}
function f2() {
console.log("f2")
}
function f3() {
console.log("f3")
}
let fns=[f1,f2,f3]
let test =(fns)=>{
//循环单个执行
fns.forEach(fn=>{
fn();
})
}
test(fns)
//f1
//f2
//f3
这种调用方式比较简单
实现方式不止这几种,像是递归或闭包也都是可以的。