over-ride a method in extended class in node js and access variable

How can I access parent prototype variable 'id' in child prototype.

const util = require('util');

const Parent = function () {};

Parent.prototype.access = function() {
    var id = 1;
};

const Child = function () {};

util.inherits(Child, Parent);

child.prototype.access = function() {
    //access Parent.prototype.access variable 'id' here
}

Any Thoughts??

1 answer

  • answered 2018-07-11 03:48 psiphi75

    You can do this using JS Classes.

    class Parent {
      constructor(id) {
        this.id = id;
      }
    
      access() {
        this.id = 1;
        console.log('Parent access');
      }
    }
    
    class Child extends Parent {
      access() {
        console.log(`Child access: ${this.id}`);
      }
    }
    
    const d = new Child(5);
    d.access(); // Child access: 5