0

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)

excentris
  • 471
  • 1
  • 7
  • 25
user544079
  • 16,109
  • 42
  • 115
  • 171
  • [possible duplicate](http://stackoverflow.com/questions/16020577/proper-prototypal-inheritance) of 45 minutes ago. Also, forget about classical, since EcmaScript (javascript) is a prototypal language. – GitaarLAB Apr 15 '13 at 17:55
  • "classical / prototypical" - which one do you mean? – Pointy Apr 15 '13 at 17:55
  • There is no _classical_ as JavaScript is a **prototypal** language... – War10ck Apr 15 '13 at 17:59
  • Fix the typos in your code: `Object.Create(baseClass)` should be `Object.create(baseclass)` and `var s = new SubClass();` should be `var s = new subClass()` – David Tansey Apr 15 '13 at 17:59
  • [here](http://ejohn.org/blog/simple-javascript-inheritance/) is an interesting article with a simple javascript inheritance implementation from John Resig that might help. – excentris Apr 15 '13 at 18:03

1 Answers1

3

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375