javascript简单链式调用案例分析

这篇文章主要介绍了javascript简单链式调用,结合具体实例形式模拟jQuery分析了链式调用的原理与具体实现技巧,需要的朋友可以参考下

本文实例讲述了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错误与调试技巧总结

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

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wysxfp.html