Javascript: Object Creation With Explicit Interfaces

I have been reading up on Javascript design patterns lately, and after having pondered the Constructor pattern and the Revealing Module Pattern, I thought, wouldn't it be nice to be able to combine the elegance of the Revealing Module Pattern with the ability to use it for more than generating singletons (modules)?

What I really love about the Revealing Module Pattern is that the returned object is a very simple description of the public interface without all of the nonsense code that should be hidden away from the user of the interface.  Example:
function Car(x,y) { //Private Fields And Methods var milesTraveled=0; var position = Position(x,y); var driveForward = function(){ //Complicated stuff } //Public interface return{ forward:driveForward, driveForward:driveForward, } }
You would create a new Car like this:
var car = Car(0,0);

Notice that you DON'T use the new keyword, because Car is a constructor and the object it creates is an anonymous map of functions we can call on Car.

No comments

Post a Comment