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

JS Inheritance example: too much recursion

Sorry for dump question I am new to js. I would like to override

f2()
function in
D
"class". But for some reason Fire Fox told me: "too much recursion". Could you please point me where recursion happening and how to make this code work as expected?

var B = function () {
};
B.prototype.f2 = function (x) {
return 2 * x;
};

var C = function () {
B.call(this);
};

var D = function () {
C.call(this);
};

D.prototype.f2 = function (x) {
return C.prototype.f2.call(this, x) * 7;
};

inherit(B, C);
inherit(C, D);

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

var d = new D();
console.log(d.f2(3));

Answer

Two problems:

  1. You need to set up the XYZ.prototype objects before you try to add properties to them. Since your inherit function creates them, you must ensure that you do things in the right order.

  2. You have the order of the parent and child backward in your inherit calls. It's inherit(child, parent), not inherit(parent, child).

var B = function () {
};
B.prototype.f2 = function (x) {
    return 2 * x;
};

var C = function () {
    B.call(this);
};
inherit(C, B);            // *** Moved and updated

var D = function () {
    C.call(this);
};
inherit(D, C);            // *** Moved and updated

D.prototype.f2 = function (x) {
    return C.prototype.f2.call(this, x) * 7;
};

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

var d = new D();
console.log(d.f2(3));

The ES2015 version, for comparison:

class B {
  f2(x) {
    return 2 * x;
  }
}

class C extends B {
}

class D extends C {
  f2(x) {
    return super.f2(x) * 7;
  }
}

const d = new D();
console.log(d.f2(3));

Comments