Yehuda Katz has a good JavaScript Function#call method entry . His entry should answer your question and many subsequent questions.
When you call a function directly using the general syntax:
var foo = function() { console.log("foo"); return this; }; foo();
Then this inside the function call is that this is outside the function call. By default, this browser has a window outside of any function calls. Thus, inside the function call, as indicated above, this also the default window .
When you call a function using the call method syntax:
var bar = { foo: function() { console.log("foo"); return this; } }; bar.foo();
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 configure a function outside the object and want to call it using this inside the function call set for the object, you can:
var foo = function() { console.log("foo"); return this; } var bar = { }; foo.call(bar);
You can also use this technique to pass arguments:
var foo = function(arg1, arg2) { console.log("foo"); return arg1 + arg2; } var bar = { }; foo.call(bar, "abc", "xyz");
yfeldblum
source share