One way to prevent global namespace pollution is by utilizing the closure pattern, where inner functions have access to their parent's properties. Through the Immediately Invoked Function Expression (IIFE), references to inner functions are returned.
There are two scenarios where the IIFE pattern proves to be beneficial and explains why the TypeScript Compiler generates it:
- During Inheritance implementation, the
BaseClass
is passed as an argument to the IIFE to avoid having it as a global variable, which would pollute the global namespace.
TypeScript:
class Greeter extends BaseController {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
JavaScript:
var Greeter = (function(_super) {
__extends(Greeter, _super);
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function() {
return "Hello, " + this.greeting;
};
return Greeter;
}(BaseController));
- For Module pattern implementation, where the application only has one global variable like 'app' and all other features are enclosed within objects such as
app.cart
, app.catalog
, etc. By using IIFE, only the necessary variables are exposed through modules while additional features are added within the modules themselves.
TypeScript:
module App.Controller {
export class Greeter extends BaseController {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
}
JavaScript:
var App;
(function (App) {
var Controller;
(function (Controller) {
var Greeter = (function (_super) {
__extends(Greeter, _super);
function Greeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return "Hello, " + this.greeting;
};
return Greeter;
}(BaseController));
Controller.Greeter = Greeter;
})(Controller = App.Controller || (App.Controller = {}));
})(App || (App = {}));
If you copy/paste this JavaScript code into your browser's console, only the 'App' variable will be globally created with the rest of the functionality contained under it.
Thank you,
mkdudeja