在封装jQuery中需要注几点
1.在jquery中 使用闭包来把内部function保存到外部 靠立即执行函数来封闭作用域
2.为了让外界可以使用jQuery 会通过window.$ = window.jquery = jquery 把jQuery保存到全局上 也就是保存到外部
3.在jQuery里它的实例函数全 都写在了实参里(简单的封装了下没有实现这个)
4.链式调用是靠 rerurn this
5.jQuery 是靠把实例函数写在构造函数jQuery.prototype.init()里
return new jQuery.prototype.init() 来包装成对象
在这里插入代码片
```(function(){
function jQuery (select){
return new jQuery.prototype.init(select); //把构造函数保存出来 包装成对象
}
jQuery.prototype.init = function(select){
//this = {} //因为是构造函数所以 底层会 this为对象
this.length = 0; //让this.length可以++
if(typeof select == 'string' && select.indexOf('.') != -1){ //判断是不是不等于-1 等于-1 是没选出来 不等于是选出来了
var dom = document.getElementsByClassName(select.slice(1)); // 把点截取掉
}else if(typeof select == 'string' && select.indexOf('#') != -1){ //判断是不是不等于-1 等于-1 是没选出来 不等于是选出来了
var dom = document.getElementById(select.slice(1));
}
//封装成类数组 操作this
if(select instanceof Element || dom.length == undefined){ //查看数组里有几位 = undefined 就是只选出来一个
this[0] = dom || select; //使this这个对象的第一位变成dom
this.length++; // 长度++
}else {
for(var i = 0 ; i < dom.length ; i ++){ //把每一位都 放在对象里 length++
this[i] = dom[i];
this.length ++;
}
}
}
window.$ = window.jQuery = jQuery; //保证jQuery还在 保存到外部形成闭包
.css()封装
jQuery.prototype.css = function(config){
for(var i = 0;i < this.length; i++){ //把类数组里的标签拿出来
for(var attr in config){ //把每个config拿出来
this[i].style[attr] = config[attr]; //把config 设在this[i]上
}
}
return this; //链式操作 拿到谁把谁再返回出去方便下次操作
}