jQuery 轻量级jQuery代码分析
已经实现的功能: each方法,map方法,toArray方法,get方法;
(function (window) {
function MHQ(selector) {
return new MHQ.fn.init(selector);
}
MHQ.fn = MHQ.prototype = {
constructor: MHQ,
type: "MHQ",
init: function (selector) {
// 判断传入的选择器类型,如果什么都不传,什么都不做
if (!selector) return this;
// 判断传入的是否是string类型
if (typeof selector === "string") {
// 判断是不是包含HTML标签的string类型
if (selector.charAt(0) === "<") {
} else { // 是选择器
[].push.apply(this, document.querySelectorAll(selector)); return this;
}
} else if (selector.constructor.name = MHQ) { // 判断传入的是否是MHQ类型
} else if (selector.nodeType) { // 判断是否是dom对象
} else if (typeof selector === "function") { // 判断是否是function
}
}
};
MHQ.fn.init.prototype = MHQ.fn;
// 此时使用 Itcast.fn.extend 扩展实例成员
// 使用 Itcast.extend 扩展静态成员
MHQ.extend = MHQ.fn.extend = function (obj) {
var k;
for (k in obj) {
this[k] = obj[k];
}
};
MHQ.fn.extend({
each: function (callback) {
return MHQ.each(this, callback);
},
map: function (callback) {
return MHQ.map(this, callback);
}
});
MHQ.extend({
each: function (obj, callback) {
var i = 0,
isArray = obj.length >= 0;
if (isArray) {
for (; i < obj.length; i++) {
if (callback.call(obj[i], i, obj[i]) === false) {
break;
}
}
} else {
for (i in obj) {
if (callback.call(obj[i], i, obj[i]) === false) {
break;
}
}
}
return obj;
},
map: function (obj, callback) {
var i = 0,
isArray = obj.length >= 0,
rect = [],
result;
if (isArray) {
for (; i < obj.length; i++) {
result = callback(obj[i], i);
if (result != null) {
return rect.push(result);
}
}
} else {
for (i in obj) {
result = callback(obj[i], i);
if (result != null) {
return rect.push(result);
}
}
}
return rect;
}
});
// 核心功能
MHQ.fn.extend({
toArray: function () {
return [].slice.call(this);
},
get: function (index) {
if (index === undefined) {
return this.toArray();
} else {
return this[index > 0 ? index : this.length + index];
}
}
});
window.MHQ = window.M = MHQ;
// DOM模块
})(window);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>01.轻量级jQuery框架搭建-实现基本功能</title>
<script src="MHQ.js"></script>
</head>
<body>
<div>1</div>
<div>3</div>
<div>2</div>
<div>4</div>
</body>
<script>
var arr = M("div").get();arr.forEach(function (v) {
v.style.width = "500px";
v.style.height = "50px";
v.style.margin = "10px 0";
v.style.border = "1px dashed #0088AA";
});
M( 'div' ).get( 1 ).style.backgroundColor = 'pink';
</script>
</html>
测试.png