Why would I attach a method to the prototype VS. the constructor function? In the simple test code below they are called the same and they produce identical results in both instances. I'm sure there must be a benefit for each method but I'm not sure what that might be.
In this first text code I attach the .totalCost()
method directly to the constructor and it works as expected in the new instance.
"use strict";
function Aircraft(a, b, c) {
this.manufacturer = a;
this.numberOfEngines = b;
this.costPerEngine = c;
this.totalCost = function() {
return this.numberOfEngines * this.costPerEngine;
}
}
let thunderbolt = new Aircraft('Republic', 1, 25000);
console.log(thunderbolt.totalCost());
In the next test code I attach the .totalCost()
method to the prototype which also works just fine in the new instance.
"use strict";
function Aircraft(a, b, c) {
this.manufacturer = a;
this.numberOfEngines = b;
this.costPerEngine = c;
Aircraft.prototype.totalCost = function() {
return this.numberOfEngines * this.costPerEngine;
}
}
let thunderbolt = new Aircraft('Republic', 1, 20000);
console.log(thunderbolt.totalCost());
Thanks so much for any input!