关于this
来源:5-6 JS 原型本章相关的面试题

Sunshine518
2021-06-16
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
})
3回答
-
双越
2021-06-16
你在 class 的 method 内部使用了 function ,导致 this 为 undefined ,如下图
如果想要正确获取 this ,可使用箭头函数,如下图
-----------
PS:在 ES5 中,所有的“自由 function”中 this 都指向 window ,但这种规范也是比较令人费解,所以 ES6 中做了修改。
032021-06-16 -
Sunshine518
提问者
2021-06-16
class jQuery {
constructor(selector) {
let elem = document.querySelectorAll(selector)
let arr = Array.from(elem)
arr.forEach(function(item, index){
console.log('this', this) //为何this是undefined
// this[index] = item
})
this.length = elem.length
}
}
let p = new jQuery('p')
console.log(p)
00 -
双越
2021-06-16
我试着 this 不是 undefined ,你在重新试试。PS:排查这个 bug ,可以把其他不相关的代码都暂时删掉,代码越少越好。
012021-06-16
相似问题