改进的地方:
- //jquery内部封装了一个Sizzle引擎来获取DOM元素document.querySelectorAll(selectors);
- //jquery为了后续操作DOM元素方便,将dom元素放在了实例对象身上//类似数组,可以用for遍历,称为伪数组
for(var i=0;i<elements.length;i++){
this[i]=elements[i];//给this创建属性从0开始的i
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>1</div>
<div>2</div>
<p>3</p>
<span id="spa">4</span>
</body>
<script type="text/javascript">
//定义一个自调函数
(function(global){
function jquery(selectors){
return new fn(selectors);
}
function Fn(selectors){
//jquery内部封装了一个Sizzle引擎来获取DOM元素
var elements=document.querySelectorAll(selectors);
//jquery为了后续操作DOM元素方便,将dom元素放在了实例对象身上
//类似数组,可以用for遍历,称为伪数组
for(var i=0;i<elements.length;i++){
this[i]=elements[i];//给this创建属性从0开始的i
}
this.length=elements.length;
}
// Fn.prototype.css=function(name,value){
// for(var i=0;i<this.length;i++){
// this[i].style[name]=value;
// }
// }
//直接替换fn的原型对象(当原型中需要定义的方法过多时使用)
Fn.prototype={
constructor:Fn,
css:function(name,value){
for(var i=0;i<this.length;i++){
this[i].style[name]=value;
}
}
}
window.$=window.jquery=jquery;//给window对象添加属性$和jquery,并设置值为jquery
})(window)
$('div').css('color','red');
$('#spa').css('color','yellow')
</script>
</html>
继续优化改进
1:在jquery第一次优化,Fn的名称改为init,将init()放入jquery原型中
2:jquery再一次优化,替换原型(将init及css方法写入jquery对象的原型中)
<body>
<div>1</div>
<div>2</div>
<p>3</p>
<span id="spa">4</span>
</body>
<script type="text/javascript">
//定义一个自调函数
(function(global){
function jquery(selectors){
return new jquery.prototype.init(selectors);
}
//改进1:在jquery第一次优化,将init()放入jquery原型中
// jquery.prototype.init=function(selectors){
// var elements=document.querySelectorAll(selectors);
// for(var i=0;i<elements.length;i++){
// this[i]=elements[i];//给this创建属性从0开始的i
// }
// this.length=elements.length;
// }
// 初始的写法:将Fn的名称改为init
// function init(selectors){
// var elements=document.querySelectorAll(selectors);
// for(var i=0;i<elements.length;i++){
// this[i]=elements[i];//给this创建属性从0开始的i
// }
// this.length=elements.length;
// }
// jquery.prototype.init.prototype={
// constructor:init,
// css:function(name,value){
// for(var i=0;i<this.length;i++){
// this[i].style[name]=value;
// }
// }
// }
// 初始写法结束
//优化2:jquery再一次优化,替换了原型
//将init函数及css方法写入jquery对象的原型中
jquery.prototype={
constructor:jquery,
init:function(selectors){
var elements=document.querySelectorAll(selectors);
for(var i=0;i<elements.length;i++){
this[i]=elements[i];//给this创建属性从0开始的i
}
this.length=elements.length;
},
css:function(name,value){
for(var i=0;i<this.length;i++){
this[i].style[name]=value;
}
}
}
//重点:为了让init实例对象访问到css方法
jquery.prototype.init.prototype=jquery.prototype;
window.$=window.jquery=jquery;//给window对象添加属性$和jquery,并设置值为jquery
})(window)
$('div').css('color','red');
$('#spa').css('color','yellow')
</script>