paint-brush
Using apply() in javascriptby@trekinbami
684 reads
684 reads

Using apply() in javascript

by Sam PakvisOctober 18th, 2016
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

After writing about <a href="https://medium.com/@trekinbami/its-not-magic-using-bind-in-javascript-18834e95cd8e#.rlkcnlwwc" target="_blank">bind()</a> and <a href="https://medium.com/@trekinbami/its-not-magic-using-call-in-javascript-640b3e29df35#.ny0afpwzh" target="_blank">call()</a>, this article will explain more on <code class="markup--code markup--p-code">apply()</code>. Those articles cover some stuff, especially about <code class="markup--code markup--p-code">this</code> and context, which is pretty important. So if you haven’t read those articles already, I really recommend you do so.
featured image - Using apply() in javascript
Sam Pakvis HackerNoon profile picture

After writing about bind() and call(), this article will explain more on apply(). Those articles cover some stuff, especially about this and context, which is pretty important. So if you haven’t read those articles already, I really recommend you do so.

Just like bind and call, apply() changes the context of this in the function you apply it to**.** If you want to know more about changing the context of this, I recommend you to read my previous articles on bind and call.

Apply does the exact same thing as call(), but with one subtle difference. Its second argument is an array of arguments, instead of the individual comma based arguments that call() requires. The first argument is, just like withcall(), the new context of this.

The comments kinda speak for themselves. But for clarity: we’re executing callOut, changing the context of callOut, and passing an Array as the single argument for apply(). You can, of course, use a million other ways to achieve the same result, but this was a short example to show you everything apply() has to offer.

And that’s it. Thanks for reading! Any questions? Reply, or send me a message on Twitter: http://twitter.com/trekinbami