Why wont this work? 16.Its All in the Genes


#1

I don't get why this won't work

// create your Animal class here
function Animal(name,numLegs){
this.name = name;
this.numLegs = numLegs;
}
// create the sayName method for Animal
Animal.prototype.sayName = function(){
console.log("Hi my name is " + name); // If I already assigned "this.name = name" in the Animal Class, why does this only work when you put console.log("Hi my name is " + this.name)?
}

// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

If I already assigned "this.name = name" in the Animal Class, why does this only work when you put console.log("Hi my name is " + this.name); ?


#2

name doesn't exist in the method so you can't access it. But the method does have access to your object so you can reference it that way (this.name).


#3

but if I'm creating a prototype from the Object Animal, then should it not know that this.name is defined as name from the Object that sayName is inheriting from?