tags:

views:

33

answers:

3

Is it better to declare fields of a class in this way:

function MyClass() {
   this.aMethod = function() {
     // code
   }
}

Or this way:

function MyClass() {
}

MyClass.prototype.aMethod = function() {
  // code
}

Any why?

Thanks in advance.

+2  A: 

The prototypal method, because it's more efficient as it adds the function to the prototype meaning any objects created with the constructor automatically get that method, while the former/first way those methods have to be created for each and every little object you make individually.

Though really it depends on what you're doing with the method. If you don't need it to be a public method then you may opt with this.method or a function statement.

meder
Thanks. By the way, what do you mean by " If you don't need it to be a public method then you may opt with this.method"? Because even if I define the method using this.aMethod = function() { ... } it will still have public visibility. I assume you mean that if I want to add a method to only one object, I can do myObject.aMethod = function() { ... } is that right?
Bytecode Ninja
+2  A: 

As @meder said, the prototypal approach is the preferred way, since the the methods are declared in the constructor's prototype, but the first approach you show us is useful to implement private members, for example:

function MyClass() {
   var privateValue = 'secret';

   function privateMethod() { }

   this.aMethod = function() {
     // privateValue and privateMethod are accessible here.
     return privateValue;
   }
}

var foo = new MyClass();
foo.aMethod(); // "secret"
foo.privateValue; // undefined !

That's what Crockford calls a privileged method, because this method has access to all the identifiers created in the lexical scope of the constructor (a closure is created).

CMS
A: 

It depends on the usage. Use the first method when you are going to use the method frequently; the second, when you are going to make rare use of it. The reason is that when the object is created with the constructor, prototypal methods are not loaded, they are only loaded when called, which will save you some performance.

Omar Abid