0

Everything I have read seems to favor declaring methods of object constructor functions in a prototype declarations instead of putting the method straight into the initial constructor.

function MyClass(name){
  this.name = name;
}

MyClass.prototype.callMethod = function(){ 
  console.log(this.name);
  };

Would this be recommended? If so what are the disadvantages to putting the method inside the initial constructor like so.

function MyClass(name){
  this.name = name;
  this.callMethod = function(){
    console.log(this.name);
    };
}

I'm assuming a case as simple as this that it doesn't really matter either way, but in cases of larger objects what are the implications in declaring the method in both stated cases?

mikeLspohn
  • 495
  • 1
  • 8
  • 21

1 Answers1

2

From Effective Javascript, Item 34: Store Methods on Prototypes:

Storing methods on a prototype makes them available to all instances without requiring multiple copies of the functions that implement them or extra properties on each instance object.

  • Storing methods on instance objects creates multiple copies of the functions, one per instance object.
  • Prefer storing methods on prototypes over storing them on instance objects.
Jeff Ogata
  • 56,645
  • 19
  • 114
  • 127
  • Thank you! This is a much simpler answer than I expected to get, but this makes perfect sense to me now. I might have to pick up Effective Javascript now. – mikeLspohn Nov 09 '14 at 23:10