dcgenjin
dcgenjin

Reputation: 1108

Constructors and prototype properties in JS

I'm figuring out prototypes in JS, and I can't figure for the life of me why this doesn't work:

var Mammal = {
    legs: 4
}

function Dog(color, soundItMakes) {
    this.prototype = Mammal;
    this.color = color;
    this.soundItMakes = soundItMakes;
    this.woof = function() { return this.soundItMakes; }
}

aDog = new Dog("brown", "beep beep!");
document.write(Mammal.legs + "<br>");
document.write(aDog.color + "<br>" + aDog.woof() + "<br>" + aDog.legs);

The first document.write() returns 4 as would be expected, but the second returns undefined for aDog.legs. Any advice would be a huge help.

Upvotes: 1

Views: 60

Answers (1)

dfsq
dfsq

Reputation: 193301

Right now prototype is the own property of the Dog instance object. So if you want you could access it like aDog.prototype.legs. However, this is not the same as setting Dog constructor prototype.

Your code should be this:

var Mammal = {
    legs: 4
}

function Dog(color, soundItMakes) {
    this.color = color;
    this.soundItMakes = soundItMakes;
    this.woof = function() { return this.soundItMakes; }
}

Dog.prototype = Mammal;

Upvotes: 1

Related Questions