TypeScript: What is the difference between declaring variables inside the constructor and outside of it?

Viewed 2128

let's assume that I have a class written in TypeScript like this:

class Messenger { 
    x = 10;
    constructor(){
      this.y = 20;
    }
};

the JavaScript version of this will look like:

var Messenger = (function () {
    function Messenger() {
        this.x = 10;
        this.y = 20;
    }
    return Messenger;
}());
;

The x and y variables are compiled to the same thing in JavaScript so what is the difference here?

Thanks.

3 Answers

Simpliest way, your code:

class Messenger { 
    x = 10;
    constructor(){
      this.y = 20;
    }
};

Is exactly the same like this:

class Messenger {
   x = 10;
   y = 20;
   constructor() { }
}

Because is the same to have this:

class Greeter {
   greeting: string;
   constructor(message: string) {
      this.greeting: string;
   }
}

that to have:

class Greeter { constructor(greeting: string) }

Actually you are doing the same, you are declaring a class property and if it is passed in the construction it will be assined, in other case it will be undefined. Is only a proper way to avoid innecesary code in TypeScript.

Related