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.?