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.
The difference is that every instance of
myFunc
shares the same single instance ofmethodTwo
, but has its own instance ofmethodOne
.I.e.
Taking this a bit further, if you are creating 1000
myFunc
instances, you are creating 1000methodOne
functions that all do the same thing. There still would be only onemethodTwo
function.