How does ‘call’ work in javascript?

Yehuda Katz has a good writeup of JavaScript’s Function#call method. His writeup should answer your question, and many followup questions besides.

When you call a function directly, using the general syntax:

var foo = function() {
  console.log("foo");
  return this;
};
foo(); // evaluates to `window`

Then this inside the function call is whatever this is outside the function call. By default, in the browser, this outside any function calls is window. So inside the function call as above, this is also by default window.

When you call a function using the method-call syntax:

var bar = {
  foo: function() {
    console.log("foo");
    return this;
  }
};
bar.foo(); // evaluates to `bar`

Then this inside the function call is the object to the left of the rightmost period: in this case, bar.

We can simulate this situation using call.

When you set up a function outside an object and want to call it with this inside the function call set to an object, you can:

var foo = function() {
  console.log("foo");
  return this;
}
var bar = { };
foo.call(bar); // evaluates to `bar`

You can use this technique to pass arguments as well:

var foo = function(arg1, arg2) {
  console.log("foo");
  return arg1 + arg2;
}
var bar = { };
foo.call(bar, "abc", "xyz"); // evaluates to `"abcxyz"`

Leave a Comment