Why do we pass the value of `this` in the `call()` and apply() functions?

Viewed 60

In the following example, the value of this is set as window.

function multiply(n1, n2) {
return n1 * n2;
}

multiply.apply(window, [3, 4]);

but in the following example, we didn't mention window

const mockingbird = {
  title: 'To Kill a Mockingbird',
  describe: function () {
    console.log(`${this.title} is a classic novel`);
  }
};

const pride = {
  title: 'Pride and Prejudice'
};

mockingbird.describe.call(pride);

I can't understand the meaning of window and when to use it

3 Answers

window is a global object available when javascript runs in the browsers.

In first code example, since multiply function is not using this, there is no need to call it with apply function and passing window object as value of this. In non-strict mode, this inside functions automatically refers to window object.

In the second example, as describe function is a method of mockingbird object, so to use it with pride object, pride is passed as a value for this

If your functions are not inside an object its outer environment will be set to the window and the keyword this will refer to it.

In your object pride you have a title and inside mockingbird you have a function describe if you want pride to get use of that describe function you have to bind it to the pride object otherwise the function will not be found so that's where call and apply come in handy.

this refers to the context where used. So if we call mokingbird.describe(), describe now has mokingbird's context. But for example if we call describe like,

let des = mokingbird.describe;
des();

Now, describe is called without context, so it will take global context which is window.

And for the first case, we are directly calling the function and using the arguments to perform actions so we do not need call or apply because they are used only when we want to call a function with different context i.e. using properties of another object in the function.

Related