Reputation: 16629
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
Reputation: 664217
First, there are two minor issues:
Object.create
needs to be lowercased, and your function names don't match (subClass
vs SubClass
). Usually, constructor function names are uppercased.this.name
(which is inherited) instead of the variable name
(which is undefined) - see Javascript: Do I need to put this.var for every variable in an object?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