var Car = function (model, year, miles) { this.model = model; this.year = year; this.miles = miles; this.carSituation = function () { console.log(this.model + this.year + this.miles); }; }; var car1 = new Car(‘bens‘, 2014, 1000); var car2 = new Car(‘mini‘, 2014, 1000); car1.carSituation(); car2.carSituation();
(1) This is a basic constructor. The internal use of this pointer to reference newly created objects has the disadvantage of making inheritance difficult.
var Car = function (model, year, miles) { this.model = model; this.year = year; this.miles = miles; }; Car.prototype.carSituation = function(){ console.log(this.model + this.year + this.miles); }; var car1 = new Car(‘bens‘, 2014, 1000); var car2 = new Car(‘mini‘, 2014, 1000); car1.carSituation(); car2.carSituation();
(2) This is a prototype constructor. You can create multiple objects and access the same prototype. Therefore, you can extend the original example.
(1) constructor (constructor)