Since I'm trying to grasp the concept of iterables in JavaScript, I built one with the following code:
let range = {
from: 0,
to: 5
};
range[Symbol.iterator] = function() {
return {
current: this.from,
last: this.to,
next() {
if (this.current <= this.last) {
return { done: false, value: this.current++ };
} else {
return { done: true };
}
}
};
};
for (let num of range) {
console.log(num);
}
The Symbol.iterator method returns an object that contains one method (next) and two properties (current and from). The properties within this object are equal to the properties within the object range.
Since current equals this.from and last equals this.to, I assumed that I could use this.from and this.to directly from within the method next as so:
let range = {
from: 0,
to: 5
};
range[Symbol.iterator] = function() {
return {
next() {
if (this.from <= this.to) {
return { done: false, value: this.from++ };
} else {
return { done: true };
}
}
};
};
for (let num of range) {
console.log(num);
}
However, doing this prevented the iteration from starting. Having observed this, I have two questions:
Why can the properties
currentandlastuse the keywordthisand have it refer to the objectrangewhereas the methodnextcannot?current,last, andnext()are all part of the same object, which is returned bySymbol.iterator.Also, given that
Symbol.iterator()returns a separate object, shouldn't thethiskeyword within that object refer to that object itself? In other words, shouldn't the propertiescurrentandlastnot be able to access the properties fromrangeusing the keywordthis? Isn'trangea separate object?