// I like this pattern..
// class
function Person(name, birthdate) {
this._name = name;
this._birthdate = birthdate;
/* should not do this
* this.getAge = function() {
* }
* as the method will be constructed
* for each instance, better to let it
* be inherited from prototype, see below
*/
}
// class methods
Person.prototype.getBirthdate = function() {
return this._birthdate;
}
// same as above, function as a method
Person.prototype.getAge = function() {
var currentDate = new Date();
// age in millis
return currentDate - this._birthdate;
}
// the get age method can be a "static"
// method on the constructor function if you pass the
// person object
Person.getAge = function(person) {
var currentDate = new Date();
// age in millis
//no reference to this
return currentDate - person.getBirthdate();
}
// you could use it like this
myPerson = new Person("Steve", new Date("1980-01-01"));
// returns age in millis
myPerson.getAge();
// returns age in millis
Person.getAge(myPerson);
You could also use a anonymous function to simulate private and public
var PersonFactory = (function() {
// private area, no one can alter
// the person cache
var _cache = {}
// public area
return {
// returns a person born now
getPerson: function(name) {
if(_cache[name]) {
return _cache[name];
}
else {
_cache[name] = new Person(name, new Date());
return _cache[name];
}
}
}
})();
var p = PersonFactory.getPerson("Leif");
p.getAge();
p = PersonFactory.getPerson("Leif");
// should be the same age / obj
p.getAge();
I don't like this pattern though. The underscore warning _myVariable should be enough to keep users of your lib from using those variables / methods. I used it allot when I first discovered it because of my Java background.. It makes it difficult to work with prototype inheritance and can cause memory leaks.