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

Node Js – get updated value from parent in child class

I am trying to update value in parent class and wants to access this in child class. But it is not giving me updated value.

class First {
    constructor() {
        this.value = 2;
    }
    updateValue() {
        this.value = 4;
        return this.value
    }
}

class Second extends First {
    constructor() {
        super()
    }

    getUpdatedValue() {
        return this.value;
    }
}
let first = new First();
console.log(first.updateValue()); // it is giving 4 i.e. updated
let second = new Second();
console.log(second.getUpdatedValue()); // but it still gives me 2

>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

You need to decide where the data is going to be. Should it be tied to an instance? Then call updateValue and getUpdatedValue from the same instance.

class First {
    constructor() {
        this.value = 2;
    }
    updateValue() {
        this.value = 4;
        return this.value
    }
}

class Second extends First {
    getUpdatedValue() {
        return this.value;
    }
}
const instance = new Second();
console.log(instance.updateValue());
console.log(instance.getUpdatedValue());

Or should the data be persistent for all instances? Then it should be a static value on the superclass.

class First {
    static value = 2;
    updateValue() {
        First.value = 4;
        return First.value
    }
}

class Second extends First {
    constructor() {
        super()
    }

    getUpdatedValue() {
        return First.value;
    }
}
let first = new First();
console.log(first.updateValue());
let second = new Second();
console.log(second.getUpdatedValue());
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