javascript简单链式调用案例分析

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

javascript简单链式调用案例分析

TBHacker   2020-05-15 我要评论

本文实例讲述了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程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们