0

I have the following code:

var Base = function () {
    // do stuff
}

Base.prototype.foo = function () {
    console.log("foo");
}

Base.prototype.someMethods = {
   methodOne: function () {
     console.log("methodOne");
   },
   methodTwo: function () {
     console.log("methodTwo");
   }
};

var myClass = function () {
    Base.call(this);
}

myClass.prototype = Object.create(Base.prototype);
myClass.constructor = myClass;

myClass.prototype.foo = function () {
    console.log("myClass")
    Base.prototype.foo.call(this);
};

myClass.prototype.someMethods.methodOne = function () {
   console.log("myClass");
   Base.prototype.someMethods.call(this);
};

When an instance of myClass is created a call to myClass.foo() will work as expected. It will calls the myClass method then calls upon the base constructor method as part of that logic.

However, myClass.prototype.someMethods.methodOne will actually overwrite Base.prototype.someMethods.methodOne (console.log(Base.prototype.someMethods.methodOne) displays the myClass function).

As a result, the call to Base.prototype.somemethods.call(this) creates infinite recursion.

Can you please explain to me why this is? How is the prototype chain being created differently for the methods of the someMethods object?

What do I need to know to get this code working properly.?

  • `Base.prototype.somemethods` doesn't have a `call` method. Did you mean `Base.prototype.somemethods.methodOne`? – Bergi Feb 02 '17 at 02:44
  • [Don't try to nest methods. Just don't.](https://stackoverflow.com/questions/15884096/organize-prototype-javascript-while-perserving-object-reference-and-inheritance) If you absolutely want nesting, make `somemethods` an instance of its own proper class with an appropriate inheritance chain – Bergi Feb 02 '17 at 02:46

0 Answers0