Today I saw two different types of Javascript function declarations and I’d like to have a deeper understanding of the two:
function Car( model, year, miles ){
this.model = model;
this.year = year;
this.miles = miles;
}
/*
Note here that we are using Object.prototype.newMethod rather than
Object.prototype so as to avoid redefining the prototype object
*/
Car.prototype.toString = function(){
return this.model + " has done " + this.miles + " miles";
};
var civic = new Car( "Honda Civic", 2009, 20000);
var mondeo = new Car( "Ford Mondeo", 2010, 5000);
console.log(civic.toString());
and type 2:
function Car( model, year, miles ){
this.model = model;
this.year = year;
this.miles = miles;
this.toString = function(){
return this.model + " has done " + this.miles + " miles";
};
}
var civic = new Car( "Honda Civic", 2009, 20000);
var mondeo = new Car( "Ford Mondeo", 2010, 5000);
console.log(civic.toString());
Specifically the ‘prototype’ and the ‘this.toString’.
Can anyone impart some pearls of JS wisdom?
The primary difference here is that in method 2 you are redefining the method with every new instance of Car you create, which is technically less performant.
One nice thing method 2 does afford you however is that you can create truly private instance variables, like so:
Another advantage to method 1 (besides performance) is that you can now change the functionality of all instances of on object. For example:
this would not be possible with method 2 (without changing it for every instance). Age however, is now exposed: