One way to define a class in Javascript is with closures and the object literal. As an example, consider a circle:
var circle = function(radius) {
var radius = radius;
return {
area: function() {
return Math.PI*(radius*radius);
}
}
}
Circle objects can then be instantiated with the internal variables remaining encapsulated:
c = circle(1);
c.area(); // Returns pi
c.radius; // Returns undefined
Unfortunately with this method, if I was to create multiple circles the area function would be copied for each instance. This is where the prototyping is usually used:
var Circle = function(radius) {
this.radius = radius;
}
Circle.prototype.area = function() {
return Math.PI*(this.radius*this.radius);
};
Now the problem is that variables cannot be declared private:
c = new Circle(1);
c.area(); // Returns pi
c.radius; // Returns 1
Does anyone know how I would get the best of both? Efficiency is an issue so would rather avoid the current formulation of the first method, and I am writing for a public API so don't want users to have access to internal variables/methods. Thanks in advance...