Samantha J T Star
Samantha J T Star

Reputation: 32808

What is the difference between setting a default value of a class property inside or outside of the constructor?

My code looks like this:

interface IConfigService {

    admin: {
        x: number;
    }

class ConfigService implements IConfigService {

    admin = this.getDefaultAdminConfigs();

    constructor() {
        this.admin = this.getDefaultAdminConfigs();
    }

private getDefaultAdminConfigs = () => {
        return {
            x: 99
        };
    }
}

Can someone tell me is there any difference between setting the value of admin outside or inside the constructor when I am using AngularJS to set up my configService?

Upvotes: 0

Views: 54

Answers (1)

basarat
basarat

Reputation: 275987

Not in your case. It is simply a matter of what gets executed last. The constructor body is executed after the inline initialization e.g. :

class Foo {
    admin = 123;
    constructor() {
        this.admin = 456;
    }
}

var foo = new Foo();
console.log(foo.admin); // 456

It might more relevant when you have an XHR in the constructor or some other property you want to init before this one.

Note: Inline initialization is also executed in order of definition.

Upvotes: 1

Related Questions