window.jQuery =function(nodeOrSelector){
let node={}//统一返回类型为伪数组对象
if(typeof nodeOrSelector==="string"){//传入字符串
let temp=document.querySelectorAll(nodeOrSelector)//查找指定元素
for(let i=0;i<temp.length;i++){//将nodeList通过中间变量temp变为伪数组对象
nodes[i]=temp[i]
}
nodes.length=temp.length;
}else if(nodeOrSelector instanceof Node){ //传入dom元素
nodes={0:nodeOrSelector,length:1} //变为长度一的伪数组对象
}
nodes.addClass=function(classes){ //添加addClass方法
for (let i = 0; i < nodes.length; i++) {
nodes[i].classList.add(classes)
}
}
nodes.setText=function(text){//添加setText方法
for(let i=0;i<nodes.length;i++){
nodes[i].textContent=text
}
}
return nodes;//返回带有方法的伪数组对象
}
window.$ = jQuery//alias模式
- 代码封装为方法,方便复用
- 通过返回新对象的方式,实现非侵入调用方法
- alias 别名