I need to create many instances of a specific class in a single page, and I’m wondering if the way that I define the methods of that class will have an impact on the page’s performance. Does it matter whether I define the methods like this:
function Foo(h, l) {
this.h = h;
this.l = l;
}
Foo.prototype.bar = function(x) {
// do stuff
}
Or this:
function Foo(h, l) {
this.h = h;
this.l = l;
this.bar = function(x) {
// do stuff
};
}
Does one offer performance benefits over the other if I have to create many instances of this class (and if the class has several other methods)? Or is there another, better way I should be using? Assume that I instantiate all of the objects using new Foo(h,l);
The first one is much preferred. In that case, there is only one definition of the
barfunction, and allFooobjects share it. In the second case, thebarfunction is being declared every single time, and each object contains their own version of it.