Skip to content

Unable to access extended properties in constructor #1617

@brenthoneybone

Description

@brenthoneybone

I'm not sure if this is an intention of typescript or not but acts differently to how I would've expected.

If i have a base class and extend it, overriding some base class properties, then want to work with the properties in the child class constructor I still access the parent properties.

This is shown in the below basic example.

class Base {

    public myVar:string = 'Base';

    public constructor() {
        console.log(this.myVar);
    }

}

class Child extends Base {

    public myVar:string = 'Child';

}

var base:Base = new Base(); // 'Base' - As expected
var child:Child = new Child(); // 'Base' - I would've expected this to be 'Child'

console.log(base.myVar); // 'Base' - As expected
console.log(child.myVar); // 'Child' - As expected

This happens in the compiled JS because the super is called before the child properties are set:

function Child() {
    _super.apply(this, arguments);
    this.myVar = 'Child';
}

Is this intended? An issue? Or a trade off because of JS limitations? Thanks!

Note that if I do something like this, it works as I would've expected. However it feels like a bit of a hacky work around.

class Base {

    public myVar:string = 'Base';

    public constructor() {
        this.setup();
    }

    protected setup() {
        console.log(this.myVar);
    }

}

class Child extends Base {

    public myVar:string = 'Child';

    public constructor() {
        super();
        this.setup();
    }

}

var base:Base = new Base(); // 'Base'
var child:Child = new Child(); // 'Child' - Now as expected

console.log(base.myVar); // 'Base'
console.log(child.myVar); // 'Child'

Metadata

Metadata

Assignees

No one assigned

    Labels

    By DesignDeprecated - use "Working as Intended" or "Design Limitation" insteadCanonicalThis issue contains a lengthy and complete description of a particular problem, solution, or design

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy