jQuery鏈式呼叫this

wade3po發表於2019-04-11

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鏈式呼叫this
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物件,相容各種場景等,暫時沒有能力去解析原始碼。

jQuery鏈式呼叫this

相關文章