In-depth understanding of the implementation of jQuery.data()
jQuery.data() is used to attach (and obtain) data to ordinary objects or DOM Elements.
The following will analyze its implementation in three parts:
1. Use name and value to append data to the object; that is, pass in three parameters, the first parameter is the object that needs to be appended with data, and the second parameter is the name of the data, and the third parameter is the value of the data. Of course, if you just get the value, you don't need to pass in the third parameter.
2. Use another object to append data to the object; that is, pass in two parameters, the first parameter is the data object that needs to be appended (we call it "obj"), and the second parameter is also an object (we Call it "another"); the key-value pairs contained in "another" will be copied to the data cache of "obj" (we call it "cache").
3. Attach data to DOM Element; DOM Element is also a kind of Object, but IE6 and IE7 have problems with garbage collection of objects directly attached to DOM Element; therefore we store these data in the global cache (we call it ("globalCache"), that is, "globalCache" contains the "cache" of multiple DOM Elements, and adds an attribute on the DOM Element to store the uid corresponding to the "cache".
Use name and value to append data to objects
When using jQuery.data() to append data to ordinary objects, the essence is to attach a "cache" to the object and use a special attribute name.
The "cache" that stores data is also an object. The data we attach to "obj" actually becomes the attribute of "cache". And "cache" is an attribute of "obj". In jQuery 1.6, the name of this attribute is "jQuery16" plus a random number (such as "jQuery16018518865841457738" mentioned below).
We can use the following code to test the functionality of jQuery.data():
<script type="text/javascript" src="jqueryjs"></script> <script> obj = {}; $data(obj, 'name', 'value'); documentwrite("$data(obj, 'name') = " + $data(obj, 'name') + '<br />'); for (var key in obj) { documentwrite("obj" + key + 'name = ' + obj[key]name); } </script>
The displayed result is:
$.data(obj, 'name') = value obj.jQuery16018518865841457738.name = value
In this code, we first append on "obj" An attribute (name is "name", value is "value"), and then the attached data is obtained through $.data(obj, 'name'). In order to gain a deeper understanding of the implementation mechanism, we have used a loop to obtain the properties of "obj", which actually removes the "cache" object attached to "obj".
You can see that jQuery.data() actually attaches "obj" to an object named "jQuery16018518865841457738" (the name is random), which is "cache". The attributes attached to the object using jquery.data() actually become attributes of this "cache".
We can use the following code to achieve a similar function:
$ = function() { var expando = "jQuery" + ("6" + Mathrandom())replace(/\D/g, ''); function getData(cache, name) { return cache[name]; } function setData(cache, name, value) { cache[name] = value; } function getCache(obj) { obj[expando] = obj[expando] || {}; return obj[expando]; } return { data : function(obj, name, value) { var cache = getCache(obj); if (value === undefined) { return getData(cache, name); } else { setData(cache, name, value); } } } }();
The first line of code in
function defines "expando", which is "jQuery1.6" plus a random number (0.xxxx), And remove the non-numeric part; this format will be used in other places in jQuery and will not be discussed here; you only need to know that this is a special name and can be used to identify different pages (such as in different iframes) "expando" will make a difference).
Next, the function getData() for obtaining data is defined, which is to obtain an attribute from "cache"; in fact, it returns cache[name].
Then there is the setData() function, which is used to set the attribute of "cache"; in fact, it is to set the value of cache[name].
is followed by getCache() to get the "cache" on "obj", that is, obj[expando]; if obj[expando] is empty, initialize it.
Finally, the data method is exposed. First, according to the incoming "obj", get the "cache" attached to "obj"; when two parameters are passed in, the getData() method is called; when three parameters are passed in , the setData() method is called.
Use another object to append data to the object
In addition to assigning values by providing name and value, we can also directly pass in another object ("another") as a parameter. In this case, the attribute name and attribute value of "another" will be treated as multiple key-value pairs, and the "name" and "value" extracted from them will be copied to the cache of the target object.
The functional test code is as follows:
<script type="text/javascript" src="jqueryjs"></script> <script> obj = {}; $data(obj, {name1: 'value1', name2: 'value2'}); documentwrite("$data(obj, 'name1') = " + $data(obj, 'name1') + '<br />' ); documentwrite("$data(obj, 'name2') = " + $data(obj, 'name2') + '<br />'); for (var key in obj) { documentwrite("obj" + key + 'name1 = ' + obj[key]name1 + '<br />'); documentwrite("obj" + key + 'name2 = ' + obj[key]name2); } </script>
The displayed result is as follows:
$.data(obj, 'name1') = value1 $.data(obj, 'name2') = value2 obj.jQuery1600233050178663064.name1 = value1 obj.jQuery1600233050178663064.name2 = value2
In the above test code, we first pass in an "another" object with two key-value pairs, Then use $.data(obj, 'name1') and $.data(obj, 'name2') to obtain additional data; similarly, in order to deeply understand the mechanism, we took out the hidden data by traversing "obj" "cache" object, and obtained the values of the "name1" attribute and "name2" attribute of the "cache" object.
You can see that jQuery.data() actually attaches an object named "obj.jQuery1600233050178663064" to "obj", which is "cache". Key-value pairs passed in using jquery.data() are copied to "cache".
We can use the following code to achieve similar functions:
$ = function() { // Other codes function setDataWithObject(cache, another) { for (var name in another) { cache[name] = another[name]; } } // Other codes return { data : function(obj, name, value) { var cache = getCache(obj); if (name instanceof Object) { setDataWithObject(cache, name) } else if (value === undefined) { return getData(cache, name); } else { setData(cache, name, value); } } } }();
这段代码是在之前的代码的基础上进行修改的。首先增加了内部函数 setDataWithObject() ,这个函数的实现是遍历 “another” 的属性,并复制到 “cache” 中。
然后,在对外开放的 data 函数中,先判断传入的第二个参数的名称,如果这个参数是一个 Object 类型的实例,则调用 setDataWithObject() 方法。
为 DOM Element 附加数据
由于 DOM Element 也是一种 Object,因此之前的方式也可以为 DOM Element 赋值;但考虑到 IE6、IE7 中垃圾回收的问题(不能有效回收 DOM Element 上附加的对象引用),jQuery采用了与普通对象有所不同的方式附加数据。
测试代码如下:
<div id="div_test" /> <script type="text/javascript" src="datajs"></script> <script> windowonload = function() { div = documentgetElementById('div_test'); $data(div, 'name', 'value'); documentwrite($data(div, 'name')); } </script>
显示结果如下:
value
测试代码中,首先通过 document.getElementById 方法获取了一个 DOM Element (当然,也可以用 jQuery 的选择器),然后在这个 DOM Element 上附加了一个属性,随后就从 DOM Element 上取出了附加的属性并输出。
因为考虑到 IE6、IE7 对 DOM Element 上的对象引用的垃圾回收存在问题,我们不会直接在 DOM Element 上附加对象;而是使用全局cache,并在 DOM Element 上附加一个 uid。
实现方式如下:
$ = function() { var expando = "jQuery" + ("6" + Mathrandom())replace(/\D/g, ''); var globalCache = {}; var uuid = 0; // Other codes function getCache(obj) { if (objnodeType) { var id = obj[expando] = obj[expando] || ++uuid; globalCache[id] = globalCache[id] || {}; return globalCache[id]; } else { obj[expando] = obj[expando] || {}; return obj[expando]; } } // Other codes }();
这段代码与之前的代码相比,增加了 globalCache 和 uuid,并修改了 getCache() 方法。
globalCache 对象用于存放附加到 DOM Element 上的 “cache”,可以视为 “cache” 的“容器”。uuid 表示 “cache” 对应的唯一标识,是唯一且自增长的。uuid 或被存放在 DOM Element 的 “expando” 属性中。
getCache() 函数中增加了一个判断,即 “obj” 具有 “nodeType” 属性,就认为这是一个 DOM Element;这种情况下,就先取出附加在 “obj” 上的 id ,即 obj[expando] ;如果 obj[expando] 未定义,则先用 ++uuid 对其进行初始化;取出 id 之后,就到 globalCache 中找到对应的 “cache” ,即 globalCache[id], 并返回。
到此为止,jQuery.data() 函数的实现就介绍完了;但是,这里还有一个需要思考的问题:为什不都统一用 “globalCache” 存储,而要将 “cache” 直接附加到普通对象上?我认为这应该是一种性能优化的方式,毕竟少一个引用的层次,存取速度应该会略快一些。 jQuery 中这刻意优化的地方非常多,在许多原本可以统一处理的对方都进行了特殊处理。但这在一定程度上,也造成了阅读源码的障碍。当然这是作者(及其他代码贡献者)本身的编程哲学,这里就不加评论了。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

jQuery is a fast, small, feature-rich JavaScript library widely used in front-end development. Since its release in 2006, jQuery has become one of the tools of choice for many developers, but in practical applications, it also has some advantages and disadvantages. This article will deeply analyze the advantages and disadvantages of jQuery and illustrate it with specific code examples. Advantages: 1. Concise syntax jQuery's syntax design is concise and clear, which can greatly improve the readability and writing efficiency of the code. for example,

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: <

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

How to tell if a jQuery element has a specific attribute? When using jQuery to operate DOM elements, you often encounter situations where you need to determine whether an element has a specific attribute. In this case, we can easily implement this function with the help of the methods provided by jQuery. The following will introduce two commonly used methods to determine whether a jQuery element has specific attributes, and attach specific code examples. Method 1: Use the attr() method and typeof operator // to determine whether the element has a specific attribute

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s
