0

What is the difference between making a method using prototype and just creating it inside a function? E.g., what's the difference between methodOne and methodTwo below?

function myFunc() {
  this.methodOne = function () { console.log("First method.")};
}

myFunc.prototype.methodTwo = function () { console.log("Second method.")};

They seem to behave the same way:

var myFuncInstance = new myFunc();
myFuncInstance.methodOne();
myFuncInstance.methodTwo();

But my sense is that methodTwo, by accessing the prototype directly, is doing something a little different.

lotstolearn
  • 91
  • 10

2 Answers2

1

The difference is that every instance of myFunc shares the same single instance of methodTwo, but has its own instance of methodOne.

I.e.

var foo = new myFunc();
var bar = new myFunc();
foo.methodOne === bar.methodOne; // false
foo.methodTwo === bar.methodTwo; // true

Taking this a bit further, if you are creating 1000 myFunc instances, you are creating 1000 methodOne functions that all do the same thing. There still would be only one methodTwo function.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
1

With using the .prototype syntax you can add methods to existing objects. For example you can add a sum method to the array type using

Array.prototype.sum = function() {...}

Then use it as

var a = [1,2,3] and then doing a.sum()

With .prototype you can just keep on extending based on your needs just as you would in a class based language.

Nu Gnoj Mik
  • 994
  • 3
  • 10
  • 25