关于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 ,如下图

//img.mukewang.com/szimg/60c9d0120940c98408080444.jpg


如果想要正确获取 this ,可使用箭头函数,如下图

//img.mukewang.com/szimg/60c9d0bc0996431b09500450.jpg


-----------

PS:在 ES5 中,所有的“自由 function”中 this 都指向 window ,但这种规范也是比较令人费解,所以 ES6 中做了修改。

0
3
Sunshine518
回复
双越
感谢老师的耐心解答
2021-06-16
共3条回复

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)

//img.mukewang.com/szimg/60c9a69308cbffeb02420070.jpg

0
0

双越

2021-06-16

我试着 this 不是 undefined ,你在重新试试。PS:排查这个 bug ,可以把其他不相关的代码都暂时删掉,代码越少越好。

//img.mukewang.com/szimg/60c9a12209184bcc12640208.jpg

0
1
Sunshine518
老师,这个是没有其他不相关代码的简洁版,结果还是undefined 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)
2021-06-16
共1条回复

一天时间高效准备前端技术一面 匹配大厂面试要求

针对时下面试高频考点,帮助新人js面试快速通关

4694 学习 · 1681 问题

查看课程

相似问题