jQuery
write Less,Do More
手写jQuery
class jQuery {
constructor(selector) {
const result = document.querySelectorAll(selector);
const length = result.length;
for (let i = 0; i < length; i++) {
this[i] = result[i];
}
this.length = length;
this.selector = selector;
//类似于数组,实际上是对象
}
// 根据index得到绑定的对象
get(index) {
return this[index]
}
// 遍历数组元素
each(fn) {
for (let i = 0; i < this.length; i++) {
const elem = this[i];
fn(elem)
}
}
// 绑定事件
on(type, fn) {
return this.each(elem => {
elem.addEventListener(type, fn, false)
})
}
//还可以扩展很多DOM操作的API
}
// 使用 自制版的jQuery
const _p = new jQuery('p');
// console.log($p);
console.log(_p.get(2));; // 得到 <p>一段文字3</p>
_p.each(elem => console.log(elem.nodeName)) // 3个p
_p.on('click', () => { alert(clicked) })//弹出 clicked
考虑插件和可扩展性
在jQuery中的原型中添加方法
可扩展性即“造轮子”
插件
由于class就是prototype的语法糖,所以就是可以在class类中增加方法
// 插件
jQuery.prototype.dialog = function (info) {
alert(info)
}
可扩展性
通过继承实现扩展
// "造轮子"
class myJquery extends jQuery {
constructor(selector) {
super(selector)
}
// 扩展自己的方法
addClass() { }
style() { }
}