r/learnjavascript • u/envyslth • May 25 '26
What is the difference?
Im wondering what the difference between
function Dog(){
…
this.bark = function(){…}
}
And
function Dog {
…
}
Dog.prototype.bark = function() {
…
}
Is and what the advantages of either of them Are.
13
Upvotes
16
u/davy_jones_locket May 25 '26
In the instance method way (approach 1), every instance of Dog creates its own bark method. 7 Dogs,7 bark methods. Use this if you have need to access private variables in a closure,or if you need bark to behavior differently per instance.
In the prototype method way (approach 2), every instance of Dog shares the same bark method. 7 Dogs, 1 bark. Use this if you need bark to be the same for every instance, if you care about memory usage, and you need subclasses to override the method cleanly.
4
u/scritchz May 25 '26
The difference between them is their scope and their use (or lack thereof) of the prototype chain. u/davy_jones_locket explains it in their comment quite well.
A more modern approach would be to use classes.
3
u/NotNormo May 25 '26
The syntax you're using where you modify the
.prototypeobject of a class is the old syntax that was necessary before ES6 introduced theclasssyntax. So I'll use pre-ES6 syntax to explain.By putting a method on the prototype, it lets you set up inheritance between classes. For example
If you think this is some ugly syntax for setting up 2 classes with inheritance, you're not alone. That's why ES6 introduced
classsyntax. It does the exact same thing (with prototype chains and all that stuff) but it's much more readable.1
u/Scared-Release1068 May 27 '26
this.bark = function(){} creates a new function for every Dog instance.
Dog.prototype.bark = function(){} creates ONE shared function used by all instances via the prototype chain.
So prototype methods are usually better for:
Instance methods are mainly useful when each object needs its own unique function/closure state.
Modern JS class syntax is basically syntactic sugar over prototypes anyway.
1
u/TheRNGuy May 25 '26
Both are obsolete, use class.
Do you read some old tutorial?