What’s the difference between this:
function Book() {
this.title = '';
this.setTitle = function(title) {
this.title = title;
}
}
or this:
function Book() {
}
Book.prototype.title = '';
Book.prototype.setTitle = function(title) {
this.title = title;
}
Is there any difference other than the syntax?
You should probably read about prototypes.
In the first example you set the function
setTitleon that veryBookinstance that gets created.In the second example you’re using prototypal inheritance, in other words all
Booksnow inherit the samesetTitlefunction.The second one saves memory and the functions are easier to “update” across all the
Bookinstances.But the first one has it’s use cases, since you can leave out the
thison title and make the variable private through the use of closures.