你的位置:首页 > 软件开发 > Java > jQuery的XX如何实现?——3.data与cache机制

jQuery的XX如何实现?——3.data与cache机制

发布时间:2016-05-11 21:00:08
往期回顾:jQuery的XX如何实现?——1.框架jQuery的XX如何实现?——2.show与链式调用--------------------------源码链接:内附实例代码jQuery使用许久了 ...

jQuery的XX如何实现?——3.data与cache机制

往期回顾:

jQuery的XX如何实现?——1.框架

jQuery的XX如何实现?——2.show与链式调用

--------------------------

源码链接:内附实例代码

jQuery使用许久了,但是有一些API的实现实在想不通。于是抽空看了jQuery源码,现在把学习过程中发现的一些彩蛋介绍给大家(⊙0⊙)。

下面将使用简化的代码来介绍,主要关注jQuery的实现思想~>_<~

相较于第一篇(与第二篇无相关性),代码更新了:27~71

 1 (function(window, undefined) { 2  3   function jQuery(sel) { 4     return new jQuery.prototype.init(sel); 5   } 6    7   jQuery.prototype = { 8     constructor: jQuery, 9     init: function(sel) {10       if(typeof sel === 'string'){11         var that = this;12         var nodeList = document.querySelectorAll(sel);13         Array.prototype.forEach.call(nodeList, function(val, i){14           that[i] = val;15         })16         this.selector = sel;17         this.length = nodeList.length;18       }19     }20   }21   22   jQuery.prototype.init.prototype = jQuery.prototype;23   24   window.$ = jQuery;25   26   27   function Data() {28     this.uid = 1;29     //原来是防篡改对象(简化一下)30     this.cache = {};31     this.expando = 'jQuery' + Math.random();32   }33   34   Data.prototype = {35     //获取elem的uid值36     key: function(elem) {37       38       var uid = elem[this.expando];39       if(!uid) {40         //为elem分配一个uid41         uid = this.uid++;42         elem[this.expando] = uid;43       }44       45       if(!this.cache[uid]) {46         this.cache[uid] = {};47       }48       49       return uid;50     },51     set: function(elem, name, val) {52       var cache = this.cache[this.key(elem)];53       cache[name] = val;54     },55     get: function(elem, name) {56       var cache = this.cache[this.key(elem)];57       return cache[name];58     }59   }60   61   var data_user = new Data();62   63   jQuery.prototype.data = function(name, val) {64     if(val) {65       Array.prototype.forEach.call(this, function(elem) {66         data_user.set(elem, name, val);67       })68       return this;69     }70     else return data_user.get(this[0], name);71   }72   73   74 })(window);

 

海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com

原标题:jQuery的XX如何实现?——3.data与cache机制

关键词:jquery

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录