Liglo App
Liglo App

Reputation: 3819

Why one cannot instantiate iterator this way?

First, have a look at this code.

var arr = [1,2,3,4];
> undefined
var si1 = arr[Symbol.iterator];
> undefined
var it1 = si1();
> Uncaught TypeError: Cannot convert undefined or null to object(…)(anonymous function) @ VM11886:2InjectedScript._evaluateOn @ VM9769:875InjectedScript._evaluateAndWrap @ VM9769:808InjectedScript.evaluate @ VM9769:664
var it2 = arr[Symbol.iterator]();
> undefined
it2.next()
> Object {value: 1, done: false}

And now the question: why the type error is produced? Is the way I call it1 not the same (or equivalent) to the way I call it2?

Upvotes: 4

Views: 119

Answers (2)

madox2
madox2

Reputation: 51931

In addition to Ryan O'Hara's answer, you can bind iterator to the correct context:

var si1 = arr[Symbol.iterator].bind(arr);
var it1 = si1();
it1.next();

Upvotes: 2

Ry-
Ry-

Reputation: 225281

When you call it as si1(), the function has a this of undefined. arr[Symbol.iterator]() sets this to arr.

Considering that

arr[Symbol.iterator] === Array.prototype[Symbol.iterator]

it has to be that the context when the function is called is what determines the result.

Upvotes: 7

Related Questions