user544079
user544079

Reputation: 16629

implementing javascript inheritance

I am trying to understand inheritance in javascript

function baseClass(name) {
   this.name = name;
   this.getName = function() {
       return this.name;
   }
}



function subClass(id, company){
       baseClass.call(this);
       this.id = id;
       this.company = company;
       this.toString = function() {
           return name + "\n" + this.id + "\n" + this.company; 
       }  
   }



subClass.prototype = Object.create(baseClass);
   var s = new subClass();
   s.toString();  //here the name property from the baseClass is not displayed.

How do correctly implement inheritance (classical / prototypical)

Upvotes: 0

Views: 74

Answers (1)

Bergi
Bergi

Reputation: 664217

First, there are two minor issues:

How do correctly implement inheritance

Move the methods (which don't need to privileged, there are no local variables in the constructor scope) on the prototype objects. And let SubClass.prototype inherit from BaseClass.prototype, not from the BaseClass function.

function BaseClass(name) {
   this.name = name;
}
BaseClass.prototype.getName = function() {
   return this.name;
};

function SubClass(id, company){
    BaseClass.call(this);
    this.id = id;
    this.company = company;
}
SubClass.prototype = Object.create(BaseClass.prototype);
SubClass.prototype.toString = function() {
   return this.name + "\n" + this.id + "\n" + this.company; 
};

new SubClass().toString() does not display the name property from the baseClass

You're calling the constructor without any arguments. The id, company and name properties will have the undefined value. Also, your SubClass doesn't even have a parameter for the name, and it doesn't pass anything to the BaseClass constructor invocation.

Upvotes: 3

Related Questions