I would like to know what is the difference between overriding methods with prototypes and without prototypes. Consider:
Example 1:
As Arun mentioned in the first example you're creating sleep and eat functions for each new instance. In the second example there's only one sleep and eat function which is shared amongst all the instances.
In this case the second method is better, but it's good to know when to use the first method and when to use the second. A little bit of theory first:
Note: There are four kinds of variables in JavaScript - private, public, shared and static.
Private variables are inaccessible outside of the function in which they are defined. For example:
function f() {
var x; // this is a private variable
}
Public variables are defined on the this object inside a function. For example:
function f() {
this.x; // this is a public variable
}
Shared variables are shared on the prototype of the function. For example:
function f() {}
f.prototype.x; // this is a shared variable
Static variables are properties of the function itself. For example:
function f() {}
f.x; // this is a static variable
Most often it's best to declare the methods of a constructor function as shared methods since all instances of the constructor share them. However if your method needs to access a private variable then it must be declared as a public method itself.
Note: This is my own nomenclature. Not many JavaScript programmers adhere to it. Others seem to follow Douglas Crockford's nomenclature: http://javascript.crockford.com/private.html
To know more about prototypal inheritance in JavaScript read the following answer: https://stackoverflow.com/a/8096017/783743