
self-jQuery
(function () {
function jQuery(selector) {
return new jQuery.prototype.init(selector); // init的原型链上有css的方法
}
jQuery.prototype.init = function (selector) {
// var this = {}
// 选出 dom 标签 并且包装成jQuery对象 返回
// id class
this.length = 0;
// null undefined
if (selector == null) {
return this;
}
if (typeof selector == 'string' && selector.indexOf('.') != -1) {
var dom = document.getElementsByClassName(selector.slice(1));
} else if (typeof selector == 'string' && selector.indexOf('#') != -1) {
var dom = document.getElementById(selector.slice(1));
}
if (selector instanceof Element || dom.length == undefined) {
// 只有一个dom
this[0] = dom || selector;
this.length++;
} else {
// 你有很多个dom Elements
// 循环dom
for (var i = 0; i < dom.length; i++) {
this[i] = dom[i] || selector[i];
this.length++;
}
}
// return this;
}
jQuery.prototype.css = function (config) {
// 循环操作每一个dom
for (var i = 0; i < this.length; i++) {
for (var attr in config) {
this[i].style[attr] = config[attr]; // 这里如果加了px那么就只能修改像素值了 对于颜色透明度就会使其失效
}
}
return this; // 链式操作的精髓 又返回了一个函数本身
}
jQuery.prototype.pushStack = function (dom) {
// dom newObject
if (dom.constructor != jQuery) {
dom = jQuery(dom);
}
dom.prevObject = this;
return dom;
}
jQuery.prototype.get = function (num) {
return num == null ? [].slice.call(this, 0) : num >= 0 ? this[num] : this[num + this.length];
}
jQuery.prototype.eq = function (num) {
var dom = num == null ? null : num >= 0 ? this[num] : this[num + this.length];
return this.pushStack(dom);
}
jQuery.prototype.add = function (selector) {
var curObj = jQuery(selector);
var baseObj = this;
var newObject = jQuery();
for (var i = 0; i < curObj.length; i++) {
newObject[newObject.length++] = curObj[i];
}
for (var i = 0; i < baseObj.length; i++) {
newObject[newObject.length++] = baseObj[i];
}
// newObject.prevObject = this;
this.pushStack(newObject);
return newObject;
}
jQuery.prototype.end = function () {
return this.prevObject;
}
jQuery.prototype.init.prototype = jQuery.prototype; // init的原型链上有css的方法
window.$ = window.jQuery = jQuery; // 内部jQuery的函数被保存到了window上所有没有被释放 就是闭包
})();
还没有评论,来说两句吧...