Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 938
Liglo App Avatar asked Jan 07 '23 20:01

Liglo App


1 Answers

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.

like image 71
Ry- Avatar answered Jan 15 '23 02:01

Ry-