mohsinulhaq
mohsinulhaq

Reputation: 1107

Difference between initializing TypeScript variables in the class itself and doing it in the constructor

class cls {
    str= 'hello';
}

vs

class cls {
    str: string;
    constructor() {
        this.str = 'hello';
    }
}

What is the difference between these two forms?

Upvotes: 0

Views: 121

Answers (3)

yash shukla
yash shukla

Reputation: 49

When you choose to initialize variables in constructor it gives you an additional benefit of initializing those values at the time of object creation like this :

var obj1= new cls("obj1"); //Ability to change variable value
var obj2= new cls("obj2");

But when you do not initialize value in constructor, then you have to first create the object and then need to access that variable to change its value like this:

var obj1= new cls(); //Two step method to initialize one value
obj1.str = "New value";

So it is always better and standard way to initialize variables in constructor this is the benefit of using object oriented programming language.

Upvotes: -1

RAVI PATEL
RAVI PATEL

Reputation: 992

There is no specific difference here.But if you write below:

class cls {
str: string;
constructor(string str) {
    this.str = str;
}

then on the time initialise of class you can assign the value to property. For example :

var obj1= new cls("obj1");
var obj2= new cls("obj2");

This won't possible with your first case.

Upvotes: 1

Sebastian Sebald
Sebastian Sebald

Reputation: 16906

There is none. This:

class Foo {
    str = 'hello';
}

class Bar {
    str: string;
    constructor() {
        this.str = 'hello';
    }
}

will result in the following output:

var Foo = (function () {
    function Foo() {
        this.str = 'hello';
    }
    return Foo;
}());
var Bar = (function () {
    function Bar() {
        this.str = 'hello';
    }
    return Bar;
}());

Upvotes: 1

Related Questions