To add a function to an object, i write it inside of it like this AddX:
function Foo()
{
this.x = 1;
this.AddX = function(y)
{
this.x += y;
}
}
But I found out that other way could be to use prototype:
function Foo()
{
this.x = 1;
}
Foo.prototype.AddX = function(y)
{
this.x += y;
}
Using:
obj = new Foo;
obj.AddX(5);
alert(obj.x);
Result is same in both cases. Which route is best or is there any difference between the two ? Is there any performance issue also ?
In your first approach,
addXis an instance method. Thus each instance ofFoowill have their own copy ofaddX.While in the second approach,
addXis a added ontoprototype, and each instance ofFooshares the same prorotype.Thus the second approach will save more memory. If you have a large number of instances to be created, then you’d better use the second approach.