javascript简单链式调用案例分析

时间:2019-03-30
本文章向大家介绍javascript简单链式调用案例分析,主要包括javascript简单链式调用案例分析使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《JavaScript数据结构与算法技巧总结》、《JavaScript数学运算用法总结》、《JavaScript排序算法总结》、《JavaScript遍历算法与技巧总结》、《JavaScript查找算法技巧总结》及《JavaScript错误与调试技巧总结

希望本文所述对大家JavaScript程序设计有所帮助。