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?

0

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.