Pijusn
Pijusn

Reputation: 11293

JavaScript Constructor Not Called

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?

Upvotes: 1

Views: 2030

Answers (1)

Luka Ramishvili
Luka Ramishvili

Reputation: 899

You return child, which is a function to print Crappy constructor. No matter what, if you call that function, Crappy constructor will be printed.

Note the flow:

child = function to print 'crappy'
child.prototype.blabla = function to print 'Awesome'
inherit returns child

NewClass = child

now, 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.

Upvotes: 2

Related Questions