javaScript链式调用的简单实现

链式调用在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

这种调用方式比较简单

实现方式不止这几种,像是递归或闭包也都是可以的。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值