javascript如何实现简单链式调用
更新:HHH   时间:2023-1-7


小编给大家分享一下javascript如何实现简单链式调用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

具体如下:

jQuery用的就是链式调用。像一条连接一样调用方法。
链式调用的核心就是return this;,每个方法都返回对象本身。

下面是简单的模拟jQuery的代码:

<script>
  window.$ = function (id) {
    return new _$(id);
  }
  function _$(id) {
    this.elements = document.getElementById(id);
  }
  _$.prototype = {
    constructor: _$,
    hide: function () {
      console.log('hide');
      return this;
    },
    show: function () {
      console.log('show');
      return this;
    },
    getName: function (callback) {
      if (callback) {
        callback.call(this, this.name);
      }
      return this;
    },
    setName: function (name) {
      this.name = name;
      return this;
    }
  }
  $('test').setName('helloworld').getName(function (name) {
    console.log(name);
  }).show().hide().show().hide().show();
</script>

运行效果图如下:

以上是“javascript如何实现简单链式调用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注天达云行业资讯频道!

返回web开发教程...