Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript functions to simulate classes, best practices?

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());
like image 604
Johan Avatar asked Nov 23 '11 13:11

Johan


1 Answers

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 (...) {...};
}
like image 65
steveyang Avatar answered Oct 06 '22 08:10

steveyang