I am new to JavaScript, and trying to understand how i should write classes (my background in ‘regular’ OO languages, such as java and c++).
I understand that i have two options:
-
If i want my class to have private methods and members i can’t define them in the prototype. But in that case, they will be built for each new object created (memory issue).
-
If i define methods in the class prototype, i will have no encapsulation (this is weird for me, as a java/c++ developer :P).
Which of the two methods you use? why?
So, I don’t think there’s a “right answer” to this question…it’s basically what you prefer and think is best for your particular use. Many of my classes are “Static classes”, e.g.
As I never need to instantiate them. When I need to instantiate multiple instances, I use the prototype method.
If you NEED private variables, you could define a function/class to do private variables, and the methods that need to access those private vars within that function/class. Then, use the prototype method for all methods that don’t need access to the private vars. E.g.
Doing both should enable you to keep your instantiation a bit lighter weight, but still give you some encapsulation. So far, I’ve never bothered with private vars.