Why is this JavaScript constructor generated by Typescript wrapped an immediately-invoked function? -


could explain me advantage of 'constructor' definition:

var tree = (function () {   function tree(name) {     this.name = name;   }   return tree; })(); 

instead of

var tree = function(name) {    this.name = name; }; 

the first variant produced typescript compiler.

in typescript's case, there closure there capturing base class

class animal {     public run() {         console.log('running!');     } }  class giraffe extends animal {     public run() {         super.run();         console.log('... , looking awkward');     } } 

emits:

var animal = (function () {     function animal() {     }     animal.prototype.run = function () {         console.log('running!');     };     return animal; })();  var giraffe = (function (_super) {     __extends(giraffe, _super);     function giraffe() {         _super.apply(this, arguments);     }     giraffe.prototype.run = function () {         _super.prototype.run.call(this);         console.log('... , looking awkward');     };     return giraffe; })(animal); 

note use of _super.prototype refer base class via parameter (animal here) passed immediately-invoked function. without closure, there'd save value without polluting global namespace.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -