Sometimes I use the Array.prototype.map methode like so :
var array = ['1', '2', '3', '4'].map(parseFloat); // the result is [1, 2, 3, 4]
parseInt takes 2 arguments it returns incorrect values in this case
Now what I'm trying to do is instead of this code :
var array = ['a', 'b', 'c', 'd'].map( function (item) {
return item.toUpperCase();
}); // the result is ['A', B', 'C', 'D']
I tried this :
var array = ['a', 'b', 'c', 'd'].map(''.toUpperCase.call);
can someone explain to me why I get an error that says :
Uncaught TypeError: ["a","b","c","d"].map is not a function
The first problem is you pass the function
''.toUpperCase.apply
which is the same asFunction.prototype.apply
: it isn't bound.What happens is equivalent to
If you bind it using
then you have a second problem:
map
doesn't pass only one parameter to your callback. It also pass the index and the whole array.You could "fix" the two problems with
(more an explanation than a fix, right)
Using
call
is easier and can be fixed:which should be written as
Side note: you were lucky to use
parseFloat
in the first example. Try withparseInt
.When you pass
''.toUpperCase.call
toArray.map
, though it will pass the argument correctly, thecall
function disintegrates fromtoUpperCase
function, which holds the implementation details.So, now the
Function.call
does have the correct argument passed to it by theArray.map
callback function, but it holds no reference to''.toUpperCase
function.So
''.toUpperCase.call("a")
is entirely different tocall("a")
, which is what is happening when you pass''.toUpperCase.call
toArray.map