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());
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/
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.
To simulate an instance property, you set inside the Constructor functions (as you did in your code):
To simulate an instance method, you setup functions in the
Constructor.prototype
which will be shared across all its instancesAdvanced Pattern
If you want to set private/privileged method, Crockford has very useful patterns available.
Private Method - only available to the constructor:
Privileged Method - can access private method and is accesible to the public: