jackdaw
jackdaw

Reputation: 2314

Difference between declaring in constructor and outside of constructor

I'm using ES6, and Angular2. What is the difference between declaring something in the constructor like this:

class Example{
    constructor(private one: SomeClass, two: SomeClass){
        this.two = two;
    } 
}

and like this:

class Example2{
    private three:String = `What's the difference?`
}

I understand so far that if I import a class, then I have to declare it via the constructor. What is the difference between one, two, and three here?

Upvotes: 1

Views: 1337

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65883

Code in the constructor will be executed at the moment an instance of the object is created. Code in the class, but outside the constructor becomes class fields/memebers that are used by the class or can be called after an instance has been made.

In your example. one and two are the names of arguments that are expected to be passed into the constructor when the class is instantiated. Those values must be passed to the constructor.

three, on the other hand, is a class "field". It is created by the class and used privately during the class' lifetime. It is not passed into the class.

So, for example, with this:

class Example{
    constructor(private one: SomeClass, two: SomeClass){
        this.two = two;
    } 
}

You would instantiate it like this:

var someClass1 = new SomeClass();
var someClass2 = new SomeClass();

var myExample = new Example(someClass1, someClass2);

But in this case:

class Example2{
    private three:String = `What's the difference?`
}

You would just instantiate is like this:

var myExample2 = new Example2();

Upvotes: 2

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658263

class Example{
    constructor(private one: SomeClass, two: SomeClass){
        this.two = two;
    } 
}

is shorthand syntax for

class Example{
    private one: SomeClass;
    constructor(one: SomeClass, two: SomeClass){
        this.one = one;
        this.two = two;
    } 
}

therefore if you have private, protected, or public before a constructor parameter, a class field is declared and initialized by the value passed to the constructor at once.

Upvotes: 1

Related Questions