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.
var MyClassName = {
methodName: function() { },
//...
}
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.
var PageClass = function() {
var _birthdate;
this.getBirthdate = function() {
return typeof(_birthdate) == "undefined" ? null : _birthdate;
}
this.setBirthdate = function( date ) {
if( typeof(date) == 'object' && date.constructor == Date ) {
_birthdate = date;
}
else {
throw "Invalid Argument Exception: PageClass.setBirthdate expects parameter of type 'Date'";
}
}
}
PageClass.prototype.doSomething = function() {
alert("DOING SOMETHING");
}
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.