I am trying to understand the prototype inheritance in Javascript. There have been several questions already asked on this, but they do not seem to address the confusion I am having.
How does JavaScript .prototype work?
What is the 'new' keyword in JavaScript?
There are also some great resources on the internet.
http://www.webdeveasy.com/javascript-prototype/
http://javascriptissexy.com/javascript-objects-in-detail/
When I read those resources, I think I understand prototypical inheritance, but when I try some tests in the browser console I realise I am missing something.
Based on the code example below:
(1) why is the added prototype function description() not visible on the parent object animal ?
(2) why is an object created after the description() function is added now missing the original object attributes: name and color?
Example:
Create a simple object.
function animal(){
var name;
var colour;
}
Create two new objects based on the prototype animal
> cat = new animal();
< animal {}
> cat.name = 'cat';
> cat.color = 'black';
> cat
< animal {name: "cat", color: "black"}
Add an attribute to one object only
> dog = new animal();
> dog.name = 'dog';
> dog.color = 'brown';
> dog.bite = 'hurts';
> dog
< animal {name: "dog", color: "brown", bite: "hurts"}
> animal.prototype.description = function(){
console.log('A ' + this.name + ' is ' + this.color); }
< function (){
console.log('A ' + this.name + ' is ' + this.color); }
Add a new function as a prototype. This all works as I expected it to.
> animal
< function animal(){
var name;
var colour;
}
> dog
< animal {name: "dog", color: "brown", bite: "hurts", description: function}
> cat
< animal {name: "cat", color: "black", description: function}
Here is the confusion. the new function description appears on both of the existing dog and cat objects, but it does not appear on the parent object animal
> cat.description;
< function (){
console.log('A ' + this.name + ' is ' + this.color); }
> cat.description();
< A cat is black
A new object cow created from the parent animal now has only the description function, but not the name or color
> cow = new animal();
< animal {description: function}
> cow
< animal {description: function}
EDIT
Based on @Quince's answer, I went back to the browser, but am still confused:
>animal = function(){
this.name;
}
<function (){
this.name;
}
>animal
<function (){
this.name;
}
>cat = new animal();
<animal {}
>cat
<animal {}
In this case the new object cat doesn't seem to inherit the name property from the parent.