Taking this list of similar questions:
- How to set up JavaScript namespace and classes properly
- Javascript namespace declaration with function-prototype
- Best OOP approach to these two small JavaScript classes
I'd concluded there are two possible ways for implementing classes and instances in JS: using an inner function or using a prototype.
So let's say we have a Box class inside the namespace BOX_LOGIC with a simple code in it. I'm able to code the following:
BOX_LOGIC.Box = (function() {
// private static
var boxCount = 0;
var classDefinition = function(x) {
x = x || 0;
var capacity = x;
var id = ++boxCount;
// public methods
this.getCapacity = function() { return capacity; };
this.getId = function() { return id; };
this.add = function(weight) {
weight = weight || 0;
if (capacity >= weight) {
capacity -= weight;
}
return capacity;
};
};
return classDefinition;
})();
As well as I'm able to code:
BOX_LOGIC.Box = (function () {
var boxCount;
var Box= function (x) {
x = x || 0;
this.capacity = x;
this.id = ++boxCount;
};
Box.prototype = {
Constructor: Box,
add: function (weight) {
weight = weight || 0;
if (this.capacity >= weight) {
this.capacity -= weight;
}
return this.capacity;
}
};
return Box;
})();
Mi question are: what is exactly the difference in using the Box prototype or not? is any approach better for any reason(cost, legibility, standard...)?
Is in the second approach any way to emulate the static idvariable? THX!
getCapacityis pretty useless in your second example. In your first one I'd prefer using a getter instead. It's worth noting that the two approaches are not mutually exclusive but can be combined.