I have the below prog
Object.prototype.inherit = function(baseConstructor) {
this.prototype = (baseConstructor.prototype);
this.prototype.constructor = this;
};
Object.prototype.method = function(name, func) {
this.prototype[name] = func;
};
function StrangeArray(){}
StrangeArray.inherit(Array);
StrangeArray.method("push", function(value) {
Array.prototype.push.call(this, value);
});
var strange = new StrangeArray();
strange.push(4);
alert(strange);
and when irun it i get stack overflow? why?
You're setting StrangeArray.prototype
to Array.prototype
. Later, you're adding a push
method to StrangeArray.prototype
(which is now the same thing as Array.prototype
). So you're effectively setting Array.prototype.push
. Your push
method calls Array.prototype.push
- i.e. itself. So it ends up just calling itself repeatedly and you get a stack overflow.