注意:获取的dom对象
var elem = document.getElementsByClassName('test')
typeof elem === "object"
Object.prototype.toString.call(elem) === "[object HTMLCollection]"
给标签元素的dom对象绑定值 或者 获取值
将值进行缓存的时候,我们用到是随机数,是jquery在初始化的时候,产生的随机数。
"use strict";
var version = "3.4.1";
jQuery.extend({
expando: "jQuery" + (version + Math.random()).replace(/\D/g, "")
})
function Data() {
// expando 随机生成 比如:jQuery34102265498103020911
this.expando = jQuery.expando + Data.uid++;
}
Data.uid = 1;
Data.prototype = {
cache: function (elem) {
return elem[this.expando] = elem[this.expando] || {};
},
set: function (elem, key, value) {
var cache = this.cache(elem);//对象是引用类型,操作cache 就是在操作elem[this.expando]对象
if(key && typeof key === "string" && value){
cache[key] = value;//实际上是添加或修改key属性
}else if(key && typeof key === "object" && value === undefined){
for(var prop in key){
cache[prop] = key[prop];
}
}
return cache;
},
get: function (elem, key) {
var cache = this.cache(elem);
if(key && typeof key === "string"){
return cache[key];//获取该属性值,若该属性不存在,结果为undefined
}
},
access: function (elem, key, value) {
if(key && typeof key === "string" && value === undefined){
return this.get(elem, key);//取值的
}else if(key && value || Object.prototype.toString.call(key) === "[object Object]" && value === undefined){
this.set(elem, key, value);//设置值的
return value !== undefined ? value : key;
}
},
remove: function (elem, key) {
if(key && typeof key === "string"){
var cache = this.cache(elem);
delete cache[key];
}
}
}
var dataPriv = new Data();//构建私有对象
var dataUser = new Data();//构建公有对象
jQuery.extend({
//可以是一对值,也可以是一个对象内包括多个键值对
data: function (elem, key, value) {
return dataUser.access(elem, key, value);
},
removeData: function (elem, key) {
dataUser.remove(elem, key);
},
//私有方法
_data: function (elem, key, value) {
return dataUser.access(elem, key, value);
}, _removeData: function () {
return dataPriv.access(elem, name, data);
}
})