I noticed that i can write functions like the one below to simulate classes. I want to know if this is the most up-to-date way of doing it. Any comments appreciated. Thanks
function Apple(type) {
this.type = type;
this.color = "red";
this.getInfo = function () {
return this.color + ' ' + this.type + ' apple';
};
}
var apple = new Apple('testapple');
apple.color = 'blue';
console.log(apple.getInfo());
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 (...) {...};
}
Nothing wrong with this implementation.
There are so many patterns in JavaScript. Please have a look.
http://addyosmani.com/resources/essentialjsdesignpatterns/book/
I also found this site is very helpful
http://bonsaiden.github.com/JavaScript-Garden/