You should probably read about prototypes.
In the first example you set the function setTitle
on that very Book
instance that gets created.
In the second example you're using prototypal inheritance, in other words all Books
now inherit the same setTitle
function.
The second one saves memory and the functions are easier to "update" across all the Book
instances.
But the first one has it's use cases, since you can leave out the this
on title and make the variable private through the use of closures.
function Book(title) {
var title = title;
this.getTitle = function() { // function keeps a reference to title
return title; // now we only have a getter, but no setter for title
// thus title is essentially private
}
}