mardi 24 février 2015

How to save memory space using JavaScript Prototype [duplicate]


Take this as an example.



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";
};
}


And we have this:



function Car( model, year, miles ) {
this.model = model;
this.year = year;
this.miles = miles;
}

Car.prototype.toString = function() {
return this.model + "has done " + this.miles + " miles";
};


And we declare two objects:



var civic = new Car("Honda Civic", 2009, 20000);
var mondeo = new Car("Ford Mondeo", 2010, 5000);


My question is : if we declare function toString inside Car(), or declare function toString outside the Car(), will this make a difference in memory space?


My thought is: the later one, declare function using prototype, outside its constructor, will save memory space, am I right? Why?


Aucun commentaire:

Enregistrer un commentaire