Reputation: 27407
Parent = (function() {
var parent = function(name) {
this.name = name;
};
parent.prototype.dostuff = function() {
console.log(this.name);
};
parent.prototype.more = function() {
console.log("this should be available on both ... " + this.name);
};
return parent;
}());
Child = (function() {
var child = function(name) {
Parent.call(this, name);
this.prototype = Object.create(Parent.prototype);
};
child.prototype.dostuff = function() {
console.log("the child class ... " + this.name);
};
child.prototype.special = function() {
console.log("only the child has this method");
};
return child;
}());
In the above my parent object has a method called "more" but when I new up the child like so .. I can't call the more method unless I prototype it out manually. What am I missing in the above that would enable me to get prototyped methods for free?
var first = new Parent("father");
var last = new Child("son");
Update with working jsfiddle
Upvotes: 1
Views: 103
Reputation: 25728
You're setting prototype on the instance, you should set it on the function itself.
this
in the constructor function refers to the object itself when you create the object with new
. But prototype is a property on a function thats used as a constructor, not on the instances.
So you want something like this:
Child = (function() {
var child = function(name) {
Parent.call(this, name);
};
child.prototype = Object.create(Parent.prototype);
child.prototype.dostuff = function() {
console.log("the child class ... " + this.name);
};
child.prototype.special = function() {
console.log("only the child has this method");
};
return child;
}());
The prototype of Child is set to a new object with parent's prototype on its prototype, allowing it to inherit everything.
Upvotes: 1