So, I don’t think there is a “right answer” to this question ... this is basically what you prefer and consider the best for your specific use. Many of my classes are “Static Classes,” for example.
var MyClassName = { methodName: function() { },
Because I never need to create them. When I need to instantiate multiple instances, I use the prototype method.
If you need private variables, you can define a function / class to execute private variables and methods that should access those private vars inside this function / class. Then use the prototype method for all methods that do not need access to private vars. For instance.
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 allow you to keep your instance a little lighter, but still give you some encapsulation. Until now, I have never worried about private vars.
source share