The second is preferable because it takes advantage of Javascript's prototypal inheritance mechanism.
Prototypes
Javascript inheritance is a cause of confusion, but it's actually fairly simple: every object has a prototype, which is an object that we will check when we try to access a property not on the original object. The prototype will, itself, have a prototype; in a simple case, like Dog
, this will probably be Object.prototype
.
In both of your examples, because of how the new
operator works, we will end up with a prototype chain that looks like this: fido->Dog.prototype->Object.prototype
. So, if we try to look for the name
property on Fido, we'll find it right there on the object. If, on the other hand, we look for the hasOwnProperty
property, we'll fail to find it on Fido, fail to find it on Dog.prototype
, and then reach Object.prototype
, where we'll find it.
In the case of sound
, your examples define it in two different places: in the first case, fido
and every other dog we create will have their own copy of the function. In the second case, Dog.prototype
will have a single copy of the function, which will be accessed by individual dogs when the method is called. This avoids wasting resources on storing duplicates of the sound
function.
It also means that we can extend the prototype chain; maybe we want a Corgi
class that inherits the sound
function from Dog
. In the second case, we can simply ensure that Dog.prototype
is in Corgi.prototype
's prototype chain; in the first, we would need to create an actual Dog and put it in the prototype chain.