I'm trying to understand JavaScript's prototypical inheritance. In the following code snippet, I attempt to call a function from within an inheriting object's function with the same name. (Essentially, I'm trying to mimic calling a "super" method).
function Base() {
}
Base.prototype.hello = function() {
return "hello";
}
function Sub() {
Base.call(this);
}
Sub.prototype.hello = function() {
return this.prototype.hello() + " world";
}
Sub.prototype = Object.create(Base.prototype);
Sub.prototype.constructor = Sub;
var sub = new Sub();
alert(sub.hello());
The result is not what I expected... sub.hello()
returns "hello"
, but I expected it to return "hello world"
. What's going wrong?