I am very new to Javascript, and having some trouble understanding the prototype chain. My understanding is that if you create an object ("cat"), and set that object's prototype to another object ("animal"), you will inherit its attributes and methods.
However in my sandbox program, I don't see that happening. I think I must have something wrong with my understanding of prototypical inheritance.
(function() {
window.onload = function() {
document.getElementById("main").innerHTML = getMessage();
}
function animal(){
this.speak = function(){
return "I am a " + this.species + ", hear me " + this.sound;
}
}
function getMessage(){
var cat = {};
cat.prototype = new animal();
cat.species = "cat";
cat.sound = "meow";
return cat.speak(); //Causing error: cat.speak() not defined
}
})()
I thought that if you set an object's prototype and attempt to access a method or attribute that doesn't exist, JS will automatically go up the prototype chain looking for that method. But I don't see that happening here and I don't understand why.
I have noticed that it does work fine when I do this:
var cat = Object(new animal());
And I'm happy to do that, but I would like to understand why the first method doesn't work.
Thank you very much for your time.