Why Embed The Javascript Class In An Anonymous Function() Call?
Solution 1:
The following is called an Immediately Invoked Function Expression:
(function(){ ... })();
It is used to keep the global scope clean. Though, in this case it isn't necessary since the return value is assigned to a variable Greeter
. The only time this pattern is useful is when you want "private" static members.
E.g.:
varGreeter = (function () {
var foo = 'foo', bar = 'bar'; /* only accessible from function's defined
in the local scope ... */functionGreeter(message) {
this.greeting = message;
}
Greeter.prototype.greet = function () {
return"Hello, " + this.greeting;
};
returnGreeter;
})();
Solution 2:
This is to allow for private members. In this example, all members are public so your two constructions are equivalent. However, if you want to provide for private members you need to hide them from the calling scope via a closure. Thus if you have a private member like so:
classGreeter {
privategreeting: string;
constructor (message: string) {
this.greeting = message;
}
greet() {
return"Hello, " + this.greeting;
}
}
You would probably get something like this:
varGreeter = (function () {
var greeting="";
functionGreeter(message) {
greeting = message;
}
Greeter.prototype.greet = function () {
return"Hello, " + greeting;
};
returnGreeter;
})();
The greeting variable will be available to any function defined inside the anonymous function, but invisible everywhere else.
Solution 3:
Besides the obvious scoping/closure reasoning. Using an anonymous function that invokes itself immediately pre-loads (interprets) the class definition. This allows any JIT optimizations to be front loaded within the execution. In short, for larger more complex applications it will improve performance.
Solution 4:
The anonymous function / self executing closure is usually used to encapsulate scope so that only the returned value is accessible outside of it. (or anything you attach to other objects, like window)
Solution 5:
The anonymous function is probably there to prevent name collition with other parts of the code. Think of it this way, inside your anonymous function, you could even declare a variable called "$" to be whatever you want, and at the same time, be using jQuery on other parts of your code without conflict.
Post a Comment for "Why Embed The Javascript Class In An Anonymous Function() Call?"