问题:

今天写代码时遇到了一个问题,代码如下

      this.timer = setTimeout(function() {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        console.log(this.cities)
        this.list = result
      }, 100)

其中最主要的问题就是倒数第三行代码输出的是undefined(在方法外输出确实有值)

经过一番排错后发现,是ES6的箭头函数() => {}function(){}定义的方法中,this的指向有问题

使用function定义的函数,this的指向随着调用环境的变化而变化的,而箭头函数中的this指向是固定不变的,一直指向的是定义函数的环境。

因此我上面的方法

解决方案:

把使用function的地方改掉,改用箭头函数的方式来定义,可以正常输出,如下:

      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((value) => {
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) {
              result.push(value)
            }
          })
        }
        console.log(this.cities)
        this.list = result
      }, 100)

或者,将函数内的this固定,如下定义一个const that = this   :

      const that = this
      this.timer = setTimeout(function() {
        const result = []
        for (let i in that.cities) {
          that.cities[i].forEach((value) => {
            if (value.spell.indexOf(that.keyword) > -1 || value.name.indexOf(that.keyword) > -1) {
              result.push(value)
            }
          })
        }
        console.log(that.cities)
        that.list = result
      }, 100)

都可以完美实现

=。=这bug吓死我了,我还以为我前面都写错了。。。(毕竟我也不是很熟练啊)

10-08 07:18