码迷,mamicode.com
首页 > Web开发 > 详细

jQuery的矿建结构小demo举例

时间:2017-01-09 21:47:39      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:多个参数   call   属性   标签   提高   实现   struct   handle   覆盖   

    (function (global) {
var document = global.document,//变成局部变量提高搜索的性能
init;
// 核心函数
function itcast(selector) {
return new itcast.fn.init(selector);
}

// 核心原型--方法库 存储所有的方法
itcast.fn = itcast.prototype = {
constructor: itcast,
length: 0//确保时伪数组对象,伪数组没有元素,但是长度属性必须有为0 才能称为伪数组
};
// 构造函数init
/*构造函数,因为函数里的变量用户无法获取到,进行操作,函数可以通过函数名拿到原型,来操作*/
init = itcast.fn.init = function (selector) {
// 处理null undefined
if (!selector) {
return this;
}
// 处理字符串
if (itcast.isString(selector)) {
// 处理Html字符串解析
if (itcast.isHTML(selector)) {
// 将html字符串 转换成 html元素
// ‘<div><p>123</p></div><div><p>456</p></div>‘
// var o = {} == {0: 1,1: 2,2: 3,length: 3};
// var ar = [1, 2, 3];
// 借调数组的push方法 伪数组存储数据 格式如{0: 1,1: 2,2: 3,length: 3}; 方便存储 和使用
Array.prototype.push.apply(this, itcast.parseHTML(selector));
}
// handle: selector
else { //处理选择器
Array.prototype.push.apply(this,
document.querySelectorAll(selector));
}
return this;
}
//处理单个节点
if (itcast.isNode(selector)) {
this[0] = selector;
this.length = 1;
return this;
}
};
//可传入多个参数的方法
itcast.extend = function () {
var args = arguments;
for (var i = 0, l = args.length; i < l; i++) {
for (var k in args[i]) {
this[k] = args[i][k];
}
}
};
//类型判断方法 和 工具类方法 是同一个函数,传如不同的对象,处理的东西不同 因此不会产生覆盖的现象
// 类型判断方法 用作过滤
itcast.extend({
isString: function (obj) {//判断是不是字符串
return typeof obj === ‘string‘;
},
isHTML: function (obj) {
//判断是不是Html字符串
/*以 “<” 开头
长度大于3
以“>” 结尾
满足以上所有条件才为真
*/
return obj.charAt(0) === ‘<‘ && obj.charAt(obj.length - 1) === ‘>‘ &&
obj.length >= 3;
},
isNode: function (obj) {//判断是不是dom节点
// !!obj 过滤无效值 并且 节点类型在obj中存在,返回
return !!obj && ‘nodeType‘ in obj;

// return !!obj && obj.nodeType;
}
});
// 工具类方法
itcast.extend({
parseHTML: function (html) {//将Html字符串解析方法
//创建div用来装innerHtml解析的标签,方便调用innerHTML属性,和node = div.firstChild。
var div = document.createElement(‘div‘),
node,
ret = [];//以数组的形式存储创建的标签,最后再以伪数组的形式存储

div.innerHTML = html;
// 遍历节点
for (node = div.firstChild; node; node = node.nextSibling) {
if (node.nodeType === 1) {
ret.push(node);
}
}
return ret;
},
each: function (obj, callback) {//遍历方法
var i = 0,
l = obj.length;

for (; i < l; i++) {
if (callback.call(obj[i], i, obj[i]) === false) {
break;
}
}
}
});
// 实现init对象继承自itcast.prototype
// init对象也 可 被称为itcast对象
init.prototype = itcast.prototype;

/*将itcast暴露在全局 给用户使用,必须暴露一个让用户操作,
不暴露用户无法操作,尽量少暴露,越多污染的可能性就会越大*/
global.$ = global.itcast = itcast;

}(window));

jQuery的矿建结构小demo举例

标签:多个参数   call   属性   标签   提高   实现   struct   handle   覆盖   

原文地址:http://www.cnblogs.com/2016-zy-3258/p/6266462.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!