javascript functions to simulate classes, best practices?
Your code works fine but not efficient enought as it gives each instance an getInfo
function. This could be avoided. You could use the following patterns to simulate classes in JS.
Basic Pattern
To simulate a class property/method, you set properties/method on the Constructor function.
function Apple() {};
Apple.classProperty = some_value;
Apple.classMethod = some_method;
To simulate an instance property, you set inside the Constructor functions (as you did in your code):
function Apple() {
this.property = some_instance_value;
};
To simulate an instance method, you setup functions in the Constructor.prototype
which will be shared across all its instances
function Apple() {};
Apple.prototype.instanceMethod = function () {...};
Advanced Pattern
If you want to set private/privileged method, Crockford has very useful patterns available.
Private Method - only available to the constructor:
function Constructor(...) {
var that = this;
var membername = value;
function membername(...) {...}
}
Privileged Method - can access private method and is accesible to the public:
function Constructor(...) {
this.membername = function (...) {...};
}