Shouldn't this work? 21. Up the food I mean prototype chain


#1

// original classes
function Animal(name, numLegs) {
this.name = name;
this.numLegs = numLegs;
this.isAlive = true;
}
function Penguin(name) {
this.name = name;
this.numLegs = 2;
}
function Emperor(name) {
this.name = name;
this.saying = "Waddle waddle";
}

// set up the prototype chain
Penguin.prototype = new Animal();
Emperor.prototype = new Penguin();

var myEmperor = new Emperor("Jules");

console.log(myEmperor.saying); // should print "Waddle waddle"
console.log(Emperor.numLegs); // should print 2
console.log(myEmperor.isAlive); // should print true

I'm more so speaking about the console.log(Emperor.numLegs); I get that it works with console.log(myEperor.numLegs); but Emperor inherits from Penguin which has "this.numLegs = 2". So I don't get how I'm wrong to using "console.log(Emperor.numLegs); Please explain somebody.


#2

In javascript there is no way to access a object constructor (class) without first initializing an object. This is why you cannot call the numLegs method.

In other programming languages like java, C, or php (class based languages) you can declare static variables or functions when creating a class and call that function without initialing the class but not in javascript.


#3

what do you mean by initializing?


#4

When you create the following variable you're creating an object using the object constructor. I referred to this as initializing:

var myEmperor = new Emperor("Jules");

myEmperor is now an object that contains the object constructor properties.

You cannon call the Object Constructor directly without first creating an object. This is why console.log(Emperor.numLegs); // should print 2 will display undeclared.


#5

I get it. This was helpful. Thank you


#7