1

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
  • 2
    Look up "IIFE", and "module pattern". Commented Mar 17, 2014 at 9:26

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.