JavaScript中的链式操作

8 篇文章 0 订阅

最近有个小伙伴遇到了个面试题,在PHP 实现Db::table()->where()->query() 这种链式操作是怎么实现的。我一时之间突然还想不出来。看了下TP 的源码给大家分享一下

有道了一哈链式这个单词chained

class  chainedClass() {
    public function a() {
        echo '调用了方法a';
        return $this;
    }
    public function b() {
        echo '调用了方法b';
        return $this;
    }
    //function ...
}
//调用

$chained = new chainedClass();
//调用ab的顺序可以无序
$chained->a()->b();

言归正传,我们看到JavaScript 中也有很多这样的操作,比如JQuery 啊,什么什么的,我们自己封装的时候也想用一个链式操作咋办呢,来呗,各位客观来看看下面呗

  • 写法一
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>

<body>
    <script>
        class test {
            constructor(name, age) {
                this.name = name
                this.age = age
            }
            a () {
                console.log('name', this.name)
                return this
            }
            b () {
                console.log('age:', this.age)
                return this
            }
        }
        let a = new test('wenqian:', 24)
        a.a().b()
    </script>
</body>

</html>
  • 写法2(兼容ES6以前的浏览器)
   let testListFun = function(){
       const a = function() {
           console.log(111)
           return this
       }

       const b = function() {
           console.log(2)
           return this
       }
       return {
           a,
           b
       }
   }
   testListFun().a().b()

至于在需要在方法之间实现这种链式操作,就要学会callapplybind 的写法,剩下的交给各位同学们自己去理解把!

@QQ: 843462167

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值