Iterator怎么用?

下面这段代码如何不报错

let obj = {
  name: "foo",
  age: 18,
  index: 0,
  [Symbol.iterator]: () => this,
  next() {
    if (this.index == 0) {
      this.index++;
      return { value: this.name, done: false }
    }
    if (this.index == 1) {
      this.index++;
      return { value: this.age, done: false }
    }
    return { done: true }
  }
}
for (let it of obj) {
  console.log(it);
}
阅读 1.7k
1 个回答
  1. 声明对象的时候,为了使其方法的 this 指向其自身,应当用 function 关键字;
  2. 当对象的方法简写为 prop(){} 的时候,效果与 function 关键字声明的具名函数类似,prop 中的 this 指向 prop

所以上面的代码,遍历器函数应当采用 function 关键字声明,next 应当用箭头函数,或手动绑定 this
类似于:

let obj = {
  name: "foo",
  age: 18,
  index: 0,
  [Symbol.iterator]: function(){
    return {
        next: () => {
            if (this.index == 0) {
                this.index++;
                return { value: this.name, done: false }
            }
            if (this.index == 1) {
                this.index++;
                return { value: this.age, done: false }
            }
            return { done: true }
        }
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题