了解原型与闭包的概念后,可以试着手写jQuery
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
.red{color: red;}
.blue{color: blue;}
.bold{font-weight: bold;}
</style>
</head>
<body>
<h1>html</h1>
<h1>css</h1>
<p>hello world!</p>
<script>
(function(){
function jQuery(selector){
return new jQuery.prototype.init(selector);
// 返回一个new init的出来的对象
}
// 公用属性 version版本
jQuery.prototype.version = "2.0";
jQuery.prototype.init = function(selector){
// this.name = "lwh";
// 选择到所有元素
var str = typeof selector;
if(str === "function"){
jQuery.ready(selector);
}else if(str === "object"){
this[0] = selector;
this.length = 1;
}else{
var elems = document.querySelectorAll(selector)
for(var i=0;i<elems.length;i++){
this[i] = elems[i]
}
// 设置 this 实例的元素
// 设置this 实例的长度
this.length = elems.length;
}
return this;
}
jQuery.prototype.each = function(fn){
// 设置this 实例的长度
for(var i=0;i<this.length;i++){
fn(this[i]);
};
return this;
}
jQuery.prototype.addClass = function(val){
this.each(function(elem){
// 匿名函数就是 fn,elem就是this[i]
elem.classList.add(val);
// 给elem 添加 val class
});
return this;
}
jQuery.prototype.removeClass = function(val){
this.each(function(elem){
elem.classList.remove(val);
});
return this;
}
jQuery.prototype.toggleClass = function(val){
this.each(function(elem){
elem.classList.toggle(val);
});
return this;
}
jQuery.prototype.on = function(type,fn){
this.each(function(elem){
elem.addEventListener(type,fn);
});
return this;
}
//实现插件扩展(全局方法,对象方法扩展)
jQuery.fn = jQuery.prototype;//起别名
jQuery.extend = jQuery.fn.extend = function(options){
var targer = this;
for(var i in options){
targer[i] = options[i]
}
//拷贝所有扩展方法
}
//创建全局方法trim
jQuery.extend({
trim:function(str){
return str.trim();
//把字符串移除掉空格,返回
}
})
//添加对象方法 显示隐藏show hide
jQuery.fn.extend({
show:function(){
this.each(function(elem){
elem.style.display = "block";
})
return this;
},
hide:function(){
this.each(function(elem){
elem.style.display = "none"
})
return this;
}
})
//用户写插件 $.fn.extend({fullpage:function(){}})
//ready
jQuery.ready = function(fn){
if(jQuery.isReady){
fn();
}else{
setTimeout(function(){
jQuery.ready(fn);
},50)
}
}
document.addEventListener("DOMContentLoaded",function(){
jQuery.isReady = true;
})
//让init方法 拥有 jquery原型上的所有方法和属性
jQuery.prototype.init.prototype = jQuery.prototype;
//定义简写模式
window.$ = window.jQuery = jQuery;
})()
</script>
<script>
$("p").on("click",function(){
$("p").toggleClass("red");
}).addClass("bold");
</script>
</body>
</html>
在控制台中打印,使用方法