<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>js实现链式调用</title> </head> <body> <div id="id">123</div> <script> window.$ = function(){ return new _$(id); } function _$(id){ this.elements = document.getElementById(id); } _$.prototype = { constructor:_$, hide:function(){ console.log('hide'); return this; }, show:function(){ console.log('shwo'); return this; }, getName:function(callback){ if(callback){ callback.call(this,this.name); } return this; }, setName:function(name){ this.name = name; return this; } } $('id').setName('ss').getName(function(name){ console.log(name); }).show().hide().show().hide().show(); </script> </body> </html>
在打印台可以看到效果。最主要的一个步骤就是return this,才可以达到链式调用的目的。