user544079
user544079

Reputation: 16639

Javascript subclass object not retaining properties / methods of base class

function Man(name){
   this.name = name || 'John';
}
Man.prototype.getName = function(){
   return this.name;
}

function Emp(id){
   this.id = id;
}
Emp.prototype = Object.create(Man.prototype);
Emp.prototype.display = function(){
  return this.id;
}

//Testing

var emp = new Emp(100);
emp.id ; // 100
emp.display() //100

However,

emp.name // undefined
emp.getName() // undefined

emp instanceof Man // true, proves inheritance

Why do emp.name and emp.getName() come as undefined

Upvotes: 1

Views: 37

Answers (1)

Felix Kling
Felix Kling

Reputation: 816840

Why do emp.name and emp.getName() come as undefined

Because you are never applying Man to the new Emp instance. You also have to call the parent constructor in the child constructor:

function Emp(id){
   Man.call(this); // call parent constructor
   this.id = id;
}

With ECMAScript 6 classes, you would have to call super:

class Emp extends Man {
    constructor(id) {
        super();
        this.id = id;
    }
}

Upvotes: 7

Related Questions