views:

56

answers:

2

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);

+3  A: 

The first one is much preferred. In that case, there is only one definition of the bar function, and all Foo objects share it. In the second case, the bar function is being declared every single time, and each object contains their own version of it.

nickf
+1  A: 

It's better to use the first method as the same bar property is shared by every Foo instance.

Eli Grey