To avoid global pollution of the namespace.
Its clousure pattern, where internal functions have access to their parents' properties. IIFE returns the LIST to internal functions.
The following are two scenarios where the IIFE pattern is quite useful and the reason why the TypeScript Compiler generates the IIFE pattern:
- Inheritance: where it passes
BaseClass as an argument to IIFE. If IIFEE were not there BaseClass , it would be a global variable, thus polluting the global namespace.
TypeScript
class Greeter extends BaseController { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } }
Js
var Greeter = (function(_super) { __extends(Greeter, _super); function Greeter(message) { this.greeting = message; } Greeter.prototype.greet = function() { return "Hello, " + this.greeting; }; return Greeter; }(BaseController));
- Implementation of the module template: where the application has only one global variable of the type βapplicationβ, and all other functions are enclosed in objects such as
app.cart , app.catalog , etc. Only the variable is displayed through the modules, and all other functions are added to the modules themselves, which is possible only for IIFE.
TypeScript
module App.Controller { export class Greeter extends BaseController { greeting: string; constructor(message: string) { this.greeting = message; } greet() { return "Hello, " + this.greeting; } } }
Js
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 = {}));
Copy / Paste this js code into your browsers console and only the global version will be created only for the App variable. The stop function will be in the application.
Thank mkdudeja
Manish kumar
source share