I have a function to implement inheritance:
inherit = function(base) {
var child = function() { console.log('Crappy constructor.'); };
child.prototype = new base;
child.prototype.constructor = child;
return child;
}
I thought I could use it like this:
var NewClass = inherit(BaseClass);
NewClass.prototype.constructor = function() {
console.log('Awesome constructor.');
}
But when I create a new instance of NewClass like this:
var instance = new NewClass();
I get message Crappy constructor. being printed to the console. Why isn’t constructor overwritten? And how do I overwrite it?
You return
child, which is a function to printCrappy constructor. No matter what, if you call that function,Crappy constructorwill be printed.Note the flow:
NewClass = childnow, when you call NewClass, child gets called.
Other than that, I think you wanted child.constructor.prototype rather than prototype.constructor.
Edit: Please see more about inheritance in Javascript here.