I was just experimenting around with the Function.prototype.call
and Function.prototype.apply
function, when I stumbled upon an error that I didn’t understand:
I wanted to trim all the elements in an array, Naturally, I would have written:
const arr = [' text 1 ', 'nntext 2 '];
arr.map(str => str.trim());
Which works just fine.
But, for some reason, all the following options give me an error :
arr.map(String.prototype.trim.call);
arr.map(''.trim.call);
// => Uncaught TypeError: undefined is not a function
arr.map(String.prototype.trim.apply);
arr.map(''.trim.apply);
// Uncaught:
// TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function
// at Array.map (<anonymous>)
But, when I call them outside of the map, or in the map but in a function, like that:
arr.map(str => ''.trim.call(str))
It runs without issue… Why is that?
2
Answers
You do not want to apply the
String.prototype.trim
to an array. You will want to map the array items. This is not the same asMath.max(...numberArray)
, because trim is neither static, nor does it take an array of arguments.You have two options:
Array.prototype.map
call:Array.prototype.map
call:If you really want this behavior, you could add a static method to the
String
class/object.There is a difference between calling a function as a method of an object or standalone. If you call it as a method the
this
will value inside the function will be set automatically to the object. If you call it "standalone"this
will beundefined
(in strict mode).It might not look like it, but in
you are calling the
.call
method of thetrim
function. Thethis
value insidecall
will refer toString.prototype.trim
, i.e. the function you want to call.In
(which is what happens in your
arr.map
example),this
inside callcall
will beundefined
.call
doesn’t know which function should be executed.Simplified example:
There are multiple ways to solve this (as you discovered yourself). Another way is to bind the
this
value of the function to a specific value (which returns a new function). It’s a bit unwieldy though:Of course you can create a helper function for that: