下面这段代码如何不报错
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);
}
this
指向其自身,应当用function
关键字;prop(){}
的时候,效果与function
关键字声明的具名函数类似,prop
中的this
指向prop
。所以上面的代码,遍历器函数应当采用
function
关键字声明,next
应当用箭头函数,或手动绑定this
。类似于: