Calling or call(ling) a function in JavaScript

What’s up?” That was the topic of my last post when we used the line to illustrate how JavaScript sees functions as an end result. Functions are created to save functionality and JS sees them as the outcome of acting upon such functionality. We may tell JavaScript that we see a brownish round piece that looks just like a potato and returns “that is a potato!”, and JavaScript may look at us with dismay and think “What’s wrong with this person? I only see ‘That is a potato!‘”.

Today I’m going to shift gears a bit to talk about calling functions as opposed to creating them.

Let’s see how a function is called in to do its magic. Here’s a simple function that adds 1 to any number you pass in when you call it:

var addOne = function (num) {
  return num + 1;
};

Call it and pass the number 3:

addOne(3);

It returns 4. The way we called the function on line 5 is actually a shortcut for the following line:

addOne.call(window,3);

Let me explain: call() is from the JavaScript library. It’s function is to call an object on the first parameter (in our example, window), pass in some data on subsequent parameters and apply this data to the object attached to .call(), which happens to be our function addOne.

As a matter of fact, the full path would have been the following:

window.addOne.call(window,3);

Why? Well, addOne is a function that belongs to the global object we know as window. So, we are telling JavaScript to call the function addOne which belongs to the browser window, and pass in 3, which is a number that also belongs to window. In truth, the second window on the right is only there to fill in that first parameter because in this case we only want the second parameter, 3,  but since we have to insert a placeholder there, might as well do it with the correct object.

Thank goodness for shortcuts because all we have to do is this: addOne(3); instead of all that mumbojumbo.

But make not mistake, read this article carefully because call may not be needed in our example, but if you understand this example, you are well on the way to understand advanced calling methods.

If this subject interests you please read my eBook
JavaScript Objects Functions and Arrays Explained

Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s