Why is it not possible to instantiate an iterator this way?

First, 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 arises: why does a type error occur? Is the way I call it1not the same (or equivalent) as I call it2?

+4
source share
2 answers

When you call it si1(), the function has thisout undefined. arr[Symbol.iterator]()sets thisin arr.

Given that

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

It should be that the context, when the function is called, determines the result.

+7
source

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

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

Source: https://habr.com/ru/post/1624235/


All Articles