Hello World Master

Tutorials, articles and quizzes on Software Development

Javascript > Articles

Understanding the call function in Javascript

The call function is confusing when you first see it in Javascript, but after you understand how this works in Javascript it makes alot more sense, check out Javascript functions for the Object oriented developer

Call allows us to use a different this context in a function that not its own.

Thats a confusing sentence to understand, so let me explain:

Lets say we have a function and in that function we have a function inside that function

function outerFunction() {
  function innerFunctionOne() {

  }

}

Now lets add a value to the this context of our outer function

function outerFunction() {
  this.value = "Our Value";

  function innerFunctionOne() {

  }
}

Great, now we have that value in our outer function. We can simply console.log this.value

But what if we wanted to console.log this.value inside out inner function?

function outerFunction() {
  this.value = "Our Value";

  function innerFunctionOne() {
    console.log(this.value);
  }

  innerFuntionOne();
}

We would get back undefined. This is because this.value is not a part of innerFunctionOne’s this context.

What we can do is a add a .call at the end and give it a parameter of this at the end.

function outerFunction() {
  this.value = "Our Value";

  function innerFunctionOne() {
    console.log(this.value);
  }

  innerFuntionOne.call(this);
}

Now this.value will be defined inside innerFunctionOne.

What if we want to pass in arguments, we can pass them in through the call function

  innerFuntionOne.call(this, one, two, three, four );

Note that we can have as many arguments as we want passed in