Reputation: 1885
In a JavaScript code, we currently create a lot of objects using Method1 (see code). Would it be better to use Method2? (using .prototype) What would the benefits be? (Espescially interested in execution speed and memory usage.)
var exampleObjectFunction1 = function(){ alert(this.exampleProperty1);};
var exampleObjectFunction2 = function(){ this.myFunction1(); };
var exeampleProperties = {
exampleProperty1: 'example',
exampleProperty2: 'example',
};
//Method1: Current instanciation method
function exampleObject1(properties) {
this.exampleProperty1 = properties.property1;
this.examplePropertyX = properties.propertyX;
this.exampleObjectFunction1 = exampleObjectFunction1;
this.exampleObjectFunction2 = exampleObjectFunction2;
};
var exampleObject1 = new exampleObject(properties);
//Method2: Using prototype (better?)
function exampleObject2(properties) {
this.exampleProperty1 = properties.property1;
this.examplePropertyX = properties.propertyX;
};
exampleObject2.prototype.exampleObjectFunction1 = exampleObjectFunction1;
exampleObject2.prototype.exampleObjectFunction2 = exampleObjectFunction2;
var exampleObject2 = new exampleObject2(properties);
Edit: I see a lot of "constructor vs prototype" comparisons. But the "constructor" codes there usually redefine the functions inside the constructor while I pre-define them in re-usable variable. I think that this is a different scheme, though I am not quite sure if it's closer to "prototype" or to "constructor".
Upvotes: 0
Views: 38
Reputation: 51841
Let's say you create 1000 objects of exampleObject1 and 1000 objects of exampleObject2.
If you want to override exampleFunction1 for all exampleObject1 objects, you have to iterate through all your objects and change it.
If you want to do it for all exampleObject2 objects, you just change it's prototype in one place.
So, from the point of code extensibility is using of prototype better choice.
Upvotes: 2