Javascript prototypes methods vs. internal methods

94 views Asked by At

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.

2

There are 2 answers

0
Felix Kling On

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.

1
Nu Gnoj Mik On

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.