I simply can't understand why it gives this error.
Here is what I tested on my chrome's console:
> var mySet; <- undefined > mySet = new Set; <- Set {} > mySet.add('foo', 'bar', 'baz') // Worked as expected <- Set {"foo"} // just the first argument was added > ['bar', 'baz'].forEach(mySet.add) X-> VM1529:1 Uncaught TypeError: Method Set.prototype.add called on incompatible receiver undefined(…)
Thanks in advance.
In this case add
method looses its internal this
context when you pass it as a callback, so you need to use bind
:
['bar', 'baz'].forEach(mySet.add.bind(mySet));
or
['bar', 'baz'].forEach((item) => mySet.add(item));
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