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.
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 () {...};
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 (...) {...};
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With