JS newb here so hope this is not a daft question.
When defining a custom object with methods what is the difference between, and pros/cons of, the following two approaches?
1 : Define methods within class definition usingthis.
function MyObj(){
this.doStuff = function(){
//method body
}
}
2 : Define methods separately using prototype.
function MyObj(){
}
MyObj.prototype.doStuff = function()
{
//method body
}
I am messing about with it at the moment and both seem to work the same so I thought I'd find the difference before I head off on a track that is going to come back and bite me on the arse later :)
Cheers all
When you use this, every instance of your "class" will have its own copy of the method.
When you use the prototype, all the instances will share that one copy of the method. Therefore, it's more efficient to declare methods on the prototype, since less memory will be required for each instance.
For example, create two instances of MyObj:
var o1 = new MyObj(),
o2 = new MyObj();
If the doStuff method is declared in the constructor, each of those instances now has a copy of that method in memory. If it was declared on the prototype, they share that one copy. When you try to call it:
o1.doStuff();
There is no doStuff property on the instance itself, so we move up the prototype chain, to MyObj.prototype, where there is a doStuff method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With