What is the calling context of an invoked method or function within another function?
In browsers, the default calling context is the window object. In various situations, how do I avoid this?
If a function is invoked — for example, by theFunction(); — within a containing function, is the invoked function’s calling context the containing function?
In these two examples
(function ()
{
something.initialize();
}());
and
(function ()
{
something.initialize.call(this);
}());
…, is the calling context the same?
They are not the same. In the following I assume you were talking about
thiswhen you mentioned context.In the first example, inside
initialize,thiswill refer tosomething. In the second one, it will refer to the global object, which iswindowin browsers.What
thisrefers to is determined by how the function was called. There are five cases:func(), calling a function “standalone”:thisrefers to the global object.new func(), calling a function as constructor method:thiswill refer to an empty object which inherits fromfunc.prototype.obj.func(), calling a function as property of an object:thiswill refer to the objectobj.func.apply(foo),func.call(foo), invoking a function withapplyorcall:thisrefers to the object passed as first argument.ECMAScript 5 also introduced
.bind()[MDN] which enables you to bindthisto a certain object, without immediately calling the function.Now you understand why in your second example, inside
initialize,thiswill refer towindow:The outer function is called “standalone” (first case), so
thisinside of it will refer towindow. Next you are passingthistocall, which setsthisinsideinitializetowindow(fourth case).Further reading:
this, explains all I write above with some examples.