Typescript namespace translation to Javascript

231 views Asked by At

For the give typescript, a class is defined within a module

module league{
    export class Player {
        first_name: string;
        last_name: string;

        constructor(first_name: string, last_name: string){
            this.first_name = first_name;
            this.last_name=last_name;
        }
    }
}

and it is translated to javascript:

var league;
(function (league) {
    var Player = (function () {
        function Player(first_name, last_name) {
            this.first_name = first_name;
            this.last_name = last_name;
        }
        return Player;
    })();
    league.Player = Player;
})(league || (league = {}));

the typescript code is easy to understand but being not so familiar with javascript, can anyone explain the logic behind the javascript it generated?

1

There are 1 answers

0
basarat On BEST ANSWER

Module

Line by line explanation of module:

var league;

So that javascript doesn't throw an error that we are using an undefined variable.

(function (league) {
}()

An immediately executing function. Required since scope is only created by functions in javascript.

league || (league = {}

So that the module can be slipt into multiple parts. If its already defined it is used, otherwise || we create it league = {}

I suppose that is what you were after. Classes are a seperate subject.

Class

Line by line. Again an immediately executing function to create a new scope (additionally it will help with inheritance, but not relevant here) :

var Player = (function () {

})();

And the body is simply a function that uses this:

    function Player(first_name, last_name) {
        this.first_name = first_name;
        this.last_name = last_name;
    }

More

to learn more about immediately executing functions and this I recommend a javascript book. e.g. JavaScript good parts.