javascript - Why does TypeScript wrap class in anonymous function? -


this question has answer here:

let's have, example, dog class:

class dog {     static food;     private static static_var = 123;      constructor(private name) {}      speak() {         console.log(this.name + ', eat ' + dog.food + ', ' + dog.static_var);     } } 

compiled js:

var dog = (function () {     function dog(name) {         this.name = name;     }      dog.prototype.speak = function () {         console.log(this.name + ', eat ' + dog.food + ', ' + dog.static_var);     };      dog.static_var = 123;     return dog; })(); 

this works equally , less complicated:

function dog(name) {     this.name = name; }  dog.prototype.speak = function () {     console.log(this.name + ', eat ' + dog.food + ', ' + dog.static_var); };  dog.static_var = 123; 

is there (other "aesthetic") reason using anonymous function wrapper?

the main difference between 2 has hoisting.

typescript compiles class assignment of function expression variable. means resulting constructor starts exist @ point of assignment. in code occurs before, dog bound undefined.

on other hand, implementation uses plain function subject hoisting -- code in scope, including code occurs before function, can invoke dog constructor.

i guess typescript prefers ensure class not exist before defined, possibly allow redefining class @ several points in same scope.


Comments

Popular posts from this blog

How has firefox/gecko HTML+CSS rendering changed in version 38? -

javascript - Complex json ng-repeat -

jquery - Cloning of rows and columns from the old table into the new with colSpan and rowSpan -