【发布时间】:2019-05-06 14:05:10
【问题描述】:
var someString = new String('hi');
someString[Symbol.iterator] = function() {
return { // this is the iterator object, returning a single element, the string "bye"
next: function() {
if (this._first) {
this._first = false;
return { value: 'bye', done: false };
} else {
return { done: true };
}
},
_first: true
};
};
此代码用于 MDN 的字符串迭代行为机制,但我无法理解变量 _first 的用法、使用原因以及声明位置。
【问题讨论】:
-
_first 不是变量,它是 this 对象的属性。
-
但在控制台中 this.first 给出“未定义”
-
this将引用不同的东西,具体取决于调用它的位置。在next函数内部,它将引用迭代器对象,该对象有一个名为_first的属性(注意下划线)。 -
这是MDN提供的例子吗?这是一个小字符串。您正在使用字符串对象这一事实似乎无关紧要。你还不如
var someObject = { [Symbol.iterator]() { ... } };得到同样的效果。
标签: javascript string ecmascript-6 iterator iteration