I'm reading Eloquent JavaScript's "The Iterator Interface" section and I have trouble understanding why we need to define MatrixIterator
function to iterate Matrix
's contents. I usually use for
inside of another for
to iterate the contents of a two-dimensional matrix, similar to this. Is it because the [Symbol.iterator]
's of each object in JS is used whenever you call the shorthand of for
loop which is for...of
?
Furthermore, am I correct to assume that the standard [Symbol.iterator]
cannot automatically iterate a two-dimensional objects and thus, the need to create MatrixIterator
and assigning it as:
Matrix.prototype[Symbol.iterator] = function() {
return new MatrixIterator(this);
};
Are we allowed to do this instead: Matrix.prototype[Symbol.iterator] = MatrixIterator;
?
Off-topic: I feel like I should know some other things more in-depth as I feel rather confused about these concepts. Could someone also elaborate what interface means? The book did mention it as:
Different pieces of such a program interact with each other through interfaces, limited sets of functions or bindings that provide useful functionality at a more abstract level, hiding their precise implementation.
and
Separating interface from implementation is a great idea. It is usually called encapsulation.
but it did not mention what implementation is.