Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript init class properties before calling super

i’m trying to convert my javascript classes from old style to new style. The problem is, that with the new style JavaScript requires that in a constructor super is called before accessing this. I have to extend a class that i am not the owner of and in that constructor it calls a method that i overwrite where i use my own properties. How to solve that?

class A {
    constructor() {
        this.create()
    }

    create() {}

    reload() {
        this.create()
    }
}

class B extends A {
    constructor(options) {
        super()
        this.options = options
    }

    create() {
        let title = this.options.title // TypeError: Cannot read properties of undefined (reading 'title')
    }
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’d make the prototype’s create a no-op, and then call a function after the super() is done.

class A {
    constructor() {
        this.create()
    }
    create() {}
}

class B extends A {
    constructor(options) {
        super()
        this.options = options
        this.createB();
    }

    createB() {
        const title = this.options.title;
        console.log(title);
    }
    create() {}
}

new B({ title: 'foo' });

I suppose you could also assign to .create after the super runs, turning it from a no-op back to your desired functionality.

class A {
    constructor() {
        this.create()
    }
    create() {}
}

function createB() {
}
class B extends A {
    constructor(options) {
        super()
        this.options = options
        this.create = () => {
            const title = this.options.title;
            console.log(title);
        };
        this.create();
    }
    create() {}
}

new B({ title: 'foo' });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading