RudziankoŇ≠ RudziankoŇ≠ - 1 month ago 23
Javascript Question

JavaScript: Inheritance in ECMAScript5

var A = function () {
this.p1 = 2;
};
A.prototype.f1 = function () {
return 7;
};
var B = function () {
inherit(A, B);
};


function inherit(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}

var b = new B();
console.log(b.p1); // get undefined here


I am new to JS, sorry for dump question. I would like to inherit
B
from
A
. What am I doing wrong?

Answer

What am I doing wrong?

Two things:

  1. You're calling inherit inside B. You should be doing it outside.

  2. Inside B, you should be calling A, e.g.

    A.call(this/*, other, args, here, if, needed*/);
    

    or

    A.apply(this, arguments);
    

    to pass on all of the arguments B received at runtime via the automatic arguments pseudo-array.

Like so:

var A = function () {
    this.p1 = 2;
};
A.prototype.f1 = function () {
    return 7;
};
var B = function () {
    A.call(this);        // <==== Added
};
inherit(A, B);           // <==== Moved

function inherit(Child, Parent) {
    Child.prototype = Object.create(Parent.prototype);
    Child.prototype.constructor = Child;
}

var b = new B();
console.log(b.p1); // get 2 here now

Comments