jQuery链式调用this

jQuery在JavaScript库中的一哥地位是不可撼动的,虽然随着这几年框架的崛起和一些大平台移除了jQuery的依赖,但不可否认jQuery还是前端开发必须掌握的技能。

jQuery的好处很多很多,其中链式调用是其中之一。网上很多说jQuery的链式调用是返回this对象,其实原理是这样的,只不过jQuery会更复杂。

jQuery自动缓存每一步的jQuery操作,返回的都是一个jQuery对象:

$('div').find('ul li').eq(2).html('第三个');

console.log($('div'));

console.log($('div').find('ul li'));

console.log( $('div').find('ul li').eq(2));
复制代码

jQuery采用了缓存和返回jQuery对象,在效率上会比非链式的更高,在调用上也更简便。

我们可以实现最简单的this返回的链式调用:

function Fn() { 

 this.get = function () {   

   console.log('get');   

   return this; 

 } 

 this.post = function () {   

   console.log('post');  

    return this; 

 }

}

Fn.prototype.delete = function () {  

  console.log('delete');

return this;

}

var fn = new Fn();

fn.get().post().delete();
复制代码

这是构造函数和实例对象的链式调用,还有更简单的:

var fn = {  

 get: function () {   

   console.log('get'); 

   return this;   

 },   

 post: function () {   

    console.log('post'); 

   return this;   

 }, 

 delete: function () {   

   console.log('delete'); 

   return this; 

 }

}

fn.get().post().delete();
复制代码

这边简单实现一下通过ID的$

function Fn(elId) {
     this.el = document.getElementById(elId);
     return this
 }
 Fn.prototype.css = function (prop, val) {
     this.el.style[prop] = val;
     return this
 }
 Fn.prototype.hidden = function () {
     this.css('display', 'none');
     return this
 }
 Fn.prototype.show = function () {
     this.css('display', 'block');
     return this
 }

 window.$ = function (el) {
     return new Fn(el)
 }

 $('test').css('width', '300px').css('height', '300px').css('background', 'red').hidden().show()
复制代码

本来我们通过var fn = new Fn('test');就能链式调用,但是我们不同ID不可能一直无创建实例对象,所以才有了

window.$ = function (el) {
      return new Fn(el)
  }
复制代码

方法函数可以这么去实现链式调用,jQuery大概的实现思路差不多也是这样,当然,jQuery实现起来是非常复杂的,需要保存每一次的dom节点返回jQuery对象,兼容各种场景等,暂时没有能力去解析源码。

转载于:https://juejin.im/post/5caea8b25188251ad646b85c

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值