When I run the following script, I get the error that sub.hello is not a function. Why not? Sub's prototype is Base and Base has the function hello. Since Sub does not have the function hello, shouldn't its prototype then be checked for the function?
function Base() {
}
Base.prototype.hello = function() {
alert("hello");
}
Sub.prototype = Base;
function Sub() {
Base.call(this);
}
var sub = new Sub();
sub.hello();
2 Answers 2
A better way to do inheritance in JavaScript is to use the Object.create function:
function Base() {
}
Base.prototype.hello = function() {
alert("hello");
}
function Sub() {
Base.call(this);
}
Sub.prototype = Object.create(Base.prototype);
// Restore constructor property
Sub.prototype.constructor = Sub;
var sub = new Sub();
sub.hello();
See jsFiddle
For further reading, check the Mozilla reference
5 Comments
Sub.prototype.constructor = Sub; since you've overridden Sub's constructor with Base's constructor.Sub.prototype to Object.create(Base.prototype) override's Sub's constructor with Base's? Also, why do we pass Base.prototype in Object.create() instead of Base?prototype.constructor for whatever reason, see link of ryeballerBase's prototype. As calling the Base's constructor is handled in Sub's constructor.The function must exist on the prototype, not on the prototype's prototype.
You've effectively done this:
Sub.prototype.prototype.hello = function () { }
So, instead of Base.prototype.hello, either use Base.hello:
function Base() { }
Base.hello = function() { alert("hello"); }
Sub.prototype = Base;
function Sub() {
Base.call(this);
}
var sub = new Sub();
sub.hello();
Or make Sub.prototype and instance of Base:
function Base() { }
Base.prototype.hello = function() { alert("hello"); }
Sub.prototype = new Base;
function Sub() {
Base.call(this);
}
var sub = new Sub();
sub.hello();
10 Comments
Object.create(Base.prototype) does not. There's nothing wrong with it, it just invokes the constructor unnecessarily.