class jQuery {
constructor(selector) {
let elem = document.querySelectorAll(selector)
for (let i = 0; i < elem.length; i++) {
this[i] = elem[i]
}
// Array.from(elem).forEach(function(item, index){
// console.log(this) //为何this是undefind
// this[index] = item
// })
//类数组
this.length = elem.length
}
get(index) {
return this[index]
}
each(fn) {
for (let i = 0; i < this.length; i++) {
fn(this[i], i, Array.from(this))
}
}
on(type, fn) {
return this.each(elem => {
elem.addEventListener(type, fn, false)
})
}
//扩展很多DOM API
}
class Child extends jQuery{
constructor(selector){
super(selector)
}
addClass(className){
return this.each((elem)=>{
elem.className = className
})
}
}
let p = new jQuery('p')
console.log(p)
p.each(function (elem, index, array) {
console.log(elem, index, array)
})
p.on('click', ()=>{
console.log(1)
})
let c = new Child('p')
c.addClass('div')
为何下面的函数中的this是undefind
Array.from(elem).forEach(function(item, index){
console.log(this) //为何this是undefind
this[index] = item
})