Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Set.prototype.add called on incompatible receiver undefined

Tags:

javascript

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.

like image 543
Washington Guedes Avatar asked May 12 '16 23:05

Washington Guedes


1 Answers

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)); 
like image 106
Yuriy Yakym Avatar answered Oct 07 '22 20:10

Yuriy Yakym