The usage of .call()
alters the context of the Immediately-Invoked Function Expression (IIFE) to match the value of the parent scope's this
.
In a browser environment, the initial this
will be set to [object Window]
, representing the global scope:
(function () {
console.log(this);
})();
The second instance will yield the same result:
(function () {
console.log(this);
}).call(this);
An important distinction arises in ECMAScript 5's strict mode
, where in the first scenario, this
will be undefined:
(function () {
'use strict';
console.log(this); // undefined
})();
However, when utilizing Strict Mode in conjunction with .call()
, we once again restore the global scope and maintain the correct this
context:
(function () {
'use strict';
console.log(this);
}).call(this);
You can view an example of this concept in action through this jsFiddle link. The key difference lies in the fact that the "normal" IIFE loses its this
context; certain CommonJS platforms assess files with a specified this
.
CoffeeScript employs this methodology to guarantee that your code retains the same this
context as the enclosing scope (the parent scope), since functions typically do not inherit their this
object from the surrounding context.
By implementing the aforementioned patterns, you can encapsulate your function logic within them to prevent cluttering the global scope and encountering variable/naming clashes. This approach enables the creation of Modules and selective return of only the required APIs, exemplified below:
var Module = (function () {
'use strict';
return {
someMethod: function () {
// perform operations
}
}
})();
// invoke the method:
Module.someMethod();
Each function establishes its own scope, thereby safeguarding your variables/functions from conflicting with each other. Additionally, access to "private" methods is achievable within these closures:
var Module = (function () {
'use strict';
var _privateMethod = function () {};
return {
someMethod: function () {
_privateMethod();
}
}
})();
This technique proves useful when concealing methods from public accessibility by users as well.