javascript logo

Functions are one of JavaScript’s most powerful features. Functions in JavaScript allow programmers to create dynamic input/output systems, code more efficiently, and they allow for management of scope. Next to objects, functions in JavaScript may be the single most important feature of the entire language!

Explore JavaScript Courses

Functions in JavaScript are special because they are like little subprograms within the context of larger programs. Functions can be executed or “called” (alternatively  “invoked”). Functions can have parameters and get passed arguments that assign values to their parameters (think of parameters as assignable variables that are private and only accessible within the bodies of their associated functions).

What’s even more interesting about functions in JavaScript is the way in which they are treated with respect to their class. In JavaScript, functions are said to be “first-class” objects, meaning that they can be passed around like any other object or value. Furthermore, and perhaps surprising to those not familiar with JavaScript conventions, functions in JavaScript come preloaded with methods/properties just like other objects. In the following text, we’ll take a look at one of the JavaScript’s often used function methods: Function.prototype.apply.

JavaScript’s Function.prototype.apply method (or simply the apply method) has two optional parameters and thus typically takes two arguments. The first parameter is an explicit assignment of the this variable within the scope of the function by which apply is being called. The second parameter is an array (or an array-like object) of the arguments that will be passed to the function on which apply is being called. Let’s take a look at an example:

Live code example: http://codepen.io/anon/pen/LNvqge?editors=0010

Brilliant! With the apply method, we were able to explicitly define the value of this within the context of our toBeCalled function (i.e., we changed this from pointing to the global/window object, to having it point to a string that we passed as argument number one of the apply method). We were also able to pass an array of values that ultimately served as arguments passed to our toBeCalled function.

Explore JavaScript Courses

And so there you have it; the basics of JavaScript’s Function.prototype.apply method. And since the method is attached to the built-in Function.prototype object that’s inherent to all JavaScript functions, it’s true that the apply method can be used with all functions in JavaScript!

Hopefully this little lesson gave you a good idea of how to use JavaScript’s apply method, and additionally, how you might apply it to your own work! 🙂

Comments