Erik Sapir Erik Sapir - 1 month ago 6
Javascript Question

Correct way to build classes in JavaScript?

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:


  1. 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).

  2. 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?

Answer

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.