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 :

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());

Leave a Reply