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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With