Javascript question on difference between

Hi, Iam little confused in what is the difference between writing method inside constructor and writing it in prototype place inside class as both are accessible to any object made with class name?
and what is the benefit of writing prototype function inside class?

Class is a factory and every object coming from the factory is an instance of that factory. If you put method inside constructor (incl. by using class fields) you create separate function instance for each instance coming out of your factory which is unnecessary usage of memory and might lead to unexpected behavior.

Yes both will be equally accessible. In the first case method will be directly on the instance and in the latter case, when JS will not find it directly, the next place it will search would be prototype of the instance.

All instances will point to the same prototype and if you, let’s say, change code inside a method it will be immediately updated for every instance. Then there is also this thing called “DRY” - imagine your app having 1000 instances of the class - this would be equivalent of writing the same function 1000 times

3 Likes

Hi,Thanks,Then which approach should be used for writing a class??