But I still don’t understand how bind(n += this | 0) works? as far as i know the first parameter is suppose to be “this” but its the value n incremented by “this” OR 0. Looks illegal to me but it works. Someone help.
The single pipe is the bitwise OR operator. Apparently, applying a bitwise OR 0 to any non-Number value will return 0 (otherwise it just returns the number). So the first time this function executes the value of this will be the global object and thus this | 0 will return 0. So (n += this | 0) will actually be (n += 0) which is just (n).
The bind method creates a new function that has its this keyword set to the provided value. So
add.bind(n += this | 0);
is creating a new function which is just the add function but with its this set to the value in the parens, which we know now on the first time through will be n + 0.
So the first time we call add, which in this example is add(1) it will return a function which is just the add function itself but with this set to n + 0 which in this case is 1 + 0 or 1. So when we execute the returned function, passing in 2 then we get:
var next = add.bind(2 += 1 | 0);
because n equals 2 (the value passed into the function) and this equals 1 (because it was set to 1 as described above). So this time the function returned will have this set to 3. And so on. Basically, the this keyword is being used to keep a running total.
I think I get it now… so it was only possible because of the bind method as its first argument is meant to be the this value which he used to accumulate the total as you said. without the valueof method, it would just return the function itself, but with it, it is able to return the n value which is also the this value in this case.