While browsing the Test-Driven JavaScript Development book, I have noticed a nice JavaScript pattern that I would like go over. I will call it extending with closure. The most basic way how to add a method to an existing class in JavaScript is to add it to the prototype:
Date.prototype.newDateMethod = function(param) {
//do something
return date;
};
But you can get much fancier than that wrapping the whole code into an anonymous closure, which allows you to have private methods inside. (well you could have private methods here to though, but still it looks like much nice way to organize the code.)
Date.prototype.newMethod = (function () {
function doSomething() {
//do something
return date;
}
function doSomethingElse() {
//do something
return doSomething();
}
return doSomethingElse;
}());