快捷导航

js链式写法没有懂 求详细解释一下

var$=function(selector){returnnew$.prototype.init(selector);};$.prototype={init:function(selector){this.el=document.querySelector(selector);console.log(this)returnthis;},on:function(event,fn){if(window.addEventListener){this.el.addEventListener(event,fn,false);}elseif(window.attachEvent){this.el.attachEvent(on+event,fn);}returnthis;},attr:function(event,val){if(!val){returnthis.el.getAttribute(event);}else{this.el.setAttribute(event,val);returnthis;}}}$.prototype.init.prototype=$.prototype;

免责声明:本内容仅代表回答者见解不代表本站观点,请谨慎对待。

版权声明:作者保留权利,不代表本站立场。

回复

使用道具 举报

参与会员2

由于所有对象都会继承其原型对象的属性和方法,所以我们可以让定义在原型对象中的那些方法都返回用以调用方法的实例对象的引用,这样就可以对那些方法进行链式调用了。
returnthis;使用回调函数从支持链式调用的方法获取数据。链式调用很适合赋值器方法,但对于取值器方法,你可能希望他们返回你要的数据而不是this(调用该方法的对象).解决方案:利用回调技术返回所要的数据.
回复

使用道具 举报

链式写法,在调用的方法的函数里,返回对象(return this)即可实现.
回复

使用道具 举报

可能感兴趣的问答

发新帖
  • 微信访问
  • 手机APP