class jQuery {
constructor(selector) {
const result = document.querySelectorAll(selector) //CSS选择器,穿过来的是一个伪数组
const length = result.length
//在这里往这个实例里添加属性,而方法是这个类的实例所共有的,所以写在外面
for (let i = 0; i < length; i++) {
this[i] = result[i]
}
this.length = length
this.selector = selector
}
get(index) {
return this[index]
}
each(fn) {
console.log(this)
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.prototype.dialog = function (info) {
alert(info)
}
// “造轮子”
class myJQuery extends jQuery {
constructor(selector) {
super(selector) //相当于surper.constructor(selector)
}
// 扩展自己的方法
addClass(className) {
}
style(data) {
}
}
const $p = new jQuery('p')
console.log($p) //这个时候已经完成了构造函数的调用
// $p 就是里面的this
$p.each(elem => {
console.log(elem.nodeName)
})
// $p.on('click', () => alert('clicked'))
手写jQuery
最新推荐文章于 2023-05-20 21:02:09 发布