0

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?

hendryau
  • 426
  • 3
  • 14

1 Answers1

0

Here you are setting a hello property on the Sub prototype, but the prototype is overriden by Object.create on the next line.

Sub.prototype.hello = function() {
    return this.prototype.hello() + " world";
}
Sub.prototype = Object.create(Base.prototype);

Switch the order of those statements, and use a reference to Base in the Sub hello method. The code should look like this:

function Base() {
}
Base.prototype.hello = function() {
    return "hello";
}

function Sub() {
    Base.call(this);
}
Sub.prototype = Object.create(Base.prototype);
Sub.prototype.hello = function() {
    return Base.prototype.hello() + " world";
}
Sub.prototype.constructor = Sub;

var sub = new Sub();
console.log(sub.hello()); // "hello world"
user2943490
  • 6,900
  • 2
  • 22
  • 38