S
S
Sergey Demin2017-11-21 01:47:03
JavaScript
Sergey Demin, 2017-11-21 01:47:03

Why is it bad to add methods to a constructor?

I have a constructor for some object. Is it necessary to throw a method into its prototype? Can I just put it in the constructor as usual? Or is it bad manners? Or what problems can I have? Why do they say that it is better to create methods outside the constructor, that is, in prototypes?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Pavel Kornilov, 2017-11-21
@joekreek

Because the constructor will duplicate the same methods each time it is instantiated. And so - each instance inherits from the prototype. With a large number of instances, there will be a significant difference in resources.

M
McBernar, 2017-11-21
@McBernar

Why do you need to rewrite the same method n times, if you can assign it to the prototype once? This is the essence of OOP. One of.

V
Vladimir, 2017-11-24
@Casufi

Here is a good example https://jsfiddle.net/4r9k4vfq/9/
In this case, each instance creates its own object in memory with the methodOne method, but all instances use a common methodTwo object.
The first case is used only when you need to use the variables created in the scope constructor (if you try to refer to _somePrivateVar in the second method, you will get an error) but you should not abuse this, since the second method gives an advantage in performance and memory consumption.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question