0

I am trying to understand what is the difference when we write:

var Foo = function (){
 this.name = 'abc';
 this.alertName1 = function(){
  alert(this.name);
 }
}

Foo.prototype.alertName2 = function(){
  alert(this.name);
 }

Both methods will be available and are correct but when to use what is the question?

falsarella
  • 12,217
  • 9
  • 69
  • 115
Sandeep
  • 69
  • 5

1 Answers1

2

When you add a function to the prototype, it only exists in one place no matter how many times you instantiate Foo.

When you add a function inside the constructor, a new copy is created every time you instantiate so it's less efficient.

johnnycardy
  • 3,049
  • 1
  • 17
  • 27
  • Or in the constructor you can have _this.func = funcName;_ to use a function defined elsewhere that exists in only one place. (An option that may make sense together with some conditional logic that selects from several possible functions.) – nnnnnn Jan 02 '14 at 07:53
  • Yeah, although you could put that conditional logic inside a function on the prototype ;-) – johnnycardy Jan 02 '14 at 07:57