36

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.

2
  • forEach(mySet.add.bind(mySet)) - .add() must use this internally...
    – dandavis
    May 12, 2016 at 23:30
  • 6
    ['bar', 'baz'].forEach(mySet.add, mySet)
    – Bergi
    May 13, 2016 at 1:24

1 Answer 1

53

In this case add method loses 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));
4
  • @user6188402: yeah. arrow function are handy when you don't need to support mobile or IE
    – dandavis
    May 12, 2016 at 23:54
  • 4
    @dandavis: Given that we use Set, we surely also can use arrow functions :-)
    – Bergi
    May 13, 2016 at 1:23
  • @Bergi: well i've been using Map and Set for years but arrows are fairly recent...
    – dandavis
    May 13, 2016 at 1:37
  • 14
    The second argument to forEach and map is thisArg: an argument to bind this to, so you can shorten this to: .map(mySet.add, mySet) (map isn't really any slower than .forEach).
    – Zaz
    Nov 27, 2016 at 22:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.