Reputation: 271
I've been trying to understand the applications of prototyping and I can't see it adding too much utility to JS as a whole.
First of all, I should probably cover my understanding of prototyping. Attached to constructor is a prototype object, and to that you can add functions. These then apply to all iterations of the "class". So let's take the following example:
function myCar(myColor, myPrice) {
var whatAmI = "A car!"; //A private, static data member
var price = myPrice; //A private, non-static data member
this.color = myColor; //A public data member
this.utility = "driving"; //A public, static data member
}
Now let's say I want to add methods to that. I have a couple ways to do this. One option is I can put it in the constructor function.
function myCar(myColor, myPrice) {
var whatAmI = "A car!"; //A private, static data member
var price = myPrice; //A private, non-static data member
this.color = myColor; //A public data member
this.utility = "driving"; //A public, static data member
this.honk = function() {
console.log("Beep");
{
}
var car1 = new myCar("blue", 1000);
car1.honk(); //Works
Another option is I can prototype it in.
myCar.prototype.honk2 = function() {
console.log("Beep");
}
car1.honk2(); //Also works
But why would I do this? If I maintain the format of keeping all my methods in the constructor function, I can include private methods in a very similar manner which leads to code consistency!
function myCar(myColor, myPrice) {
var whatAmI = "A car!"; //A private, static data member
var price = myPrice; //A private, non-static data member
this.color = myColor; //A public data member
this.utility = "driving"; //A public, static data member
this.honk = function() {
console.log("Beep");
}
this.honkTwice = function() {
superSecretTransform();
}
var superSecretTransform = function() {
console.log("NOW I AM A JET"); //I can't access this directly!
}
}
Is there something fundamentally wrong with how I am approaching JavaScript? When should I care about the dynamic data member / method declarations allowed by prototyping?
Upvotes: 0
Views: 58
Reputation: 12161
If you have a loop that will call a function (say every frame) and inside it you create a new myCar
, it would create the same function in every call. If you put it outside the contructor function, the function will be called only once ... that is a great performance improvement.
Upvotes: 2