bind(). This article is the first of a three-parter covering them, starting with
Invoking Functions with call()
call() function method, well, calls a function. The first argument it accepts is the object to use for
this (more on this later). The rest are arguments to be passed along to the function being called (if any). The following example invokes
sayThings() twice, with the same result both times.
Alright, that seems pretty useless, but stay with me. The good stuff comes when we start playing with
this. By changing what
this is, we can control the scope in which a function is invoked.
Wrangling Function Arguments
Every function auto-magically has an array-like local variable named
arguments that provides the (you guessed it) incoming arguments.
Notice I said
arguments was array-like. Although it stores a sequence of values just like an array does, it doesn’t have any of the nice methods for working with those values.
arguments could borrow those handy array methods… Good news! It can, thanks to
Be careful, though.
join() is safe, but many other array methods make in-place alterations that can change your incoming arguments. Take
reverse(), for example.
Done intentionally, this might have clever applications, but the potential for unexpected side effects is huge. It’s probably safer to copy the arguments to a new array and do your meddling there. Fortunately,
Array.prototype.slice() makes copying easy, and
arguments can borrow it with
If you prefer shorter code, you can use
, although it is slightly less efficient to run.
call() is useful because it lets you change what
this is. Such a thing might seem weird at first, but hopefully I’ve shown how useful it can be.
That’s all for now. Next up: