通过阅读jquery原代码, 我们可以模拟写一个简单的jquery
比如常用的
jQuery("div").css("color","red");
jQuery("#span1").css("color","green");
1. jQuery(), 因为是链式调用, 所以返回是一个对象。
jQuery = function(selector){
return new jQuery.prototype.init(selector);
}
jQuery.prototype = {
constructor:jQuery,
init:function(selector){
this.elements = document.querySelectorAll(selector);
},
css:function(key, value){
......
}
}
此时,this.elements为所有合条件的html elements
2. css(), 对所有合适条件的element设置样式。
css:function(key, value){
this.elements.forEach(element => {
element.style[key] = value;
});
}
3. 此时,css是访问不了this.elements的。 因为this.elements是在init定义,并且init是构造函数。所以this.elements是init实例里面的属性。
jQuery.prototype.init.prototype=jQuery.prototype;
这样 css()就能访问this.elements.
完整代码
jQuery = function(selector){
return new jQuery.prototype.init(selector);
}
jQuery.prototype = {
constructor:jQuery,
init:function(selector){
this.elements = document.querySelectorAll(selector);
},
css:function(key, value){
this.elements.forEach(element => {
element.style[key] = value;
});
}
}
jQuery.prototype.init.prototype=jQuery.prototype;
最后起个别名
jQuery.fn=jQuery.prototype
jQuery = function(selector){
return new jQuery.fn.init(selector);
}
jQuery.fn = jQuery.prototype = {
constructor:jQuery,
init:function(selector){
this.elements = document.querySelectorAll(selector);
},
css:function(key, value){
this.elements.forEach(element => {
element.style[key] = value;
});
}
}
jQuery.fn.init.prototype=jQuery.fn;
测试一下。
<html lang="en">
<head>
<title>My jquery</title>
</head>
<body>
<div>
div 1
</div>
<div>
div 2
</div>
<span id="span1">
span 1
</span>
</body>
<script type="text/javascript">
jQuery = function(selector){
return new jQuery.fn.init(selector);
}
jQuery.fn = jQuery.prototype = {
constructor:jQuery,
init:function(selector){
this.elements = document.querySelectorAll(selector);
},
css:function(key, value){
this.elements.forEach(element => {
element.style[key] = value;
});
}
}
jQuery.fn.init.prototype=jQuery.fn;
jQuery("div").css("color","red");
jQuery("#span1").css("color","green");
</script>
</html>