I am working to optimize my practices in JS but yet I could not construct a perfect benchmark to answer me the following questions.
What is the best structure of a JS "Class"?
I have tried each of the following without any obvious performance peak.
(function() { // Scope! as a JS function
//0.example
var A = new function() {
this.x = 0; // Will be constructed on runtime initiation
A.prototype.afunc = function() {
// do something
return this;
};
};
//1.example
var B = new function() {
var x = 0;
B.prototype.bfunc = function() {
// do something
return this;
};
};
//2.example
var C = new function() {
var x = 0;
this.cfunc = function() {
// do something
return this;
};
};
//3.example
function D() { // old fashion way
var x = 0;
function dfunc() {
// do something
return this;
};
};
//4.example
var E = { // Interface style, but works perfect as an Enum style but I can't extend it
x: 0,
efunc: function() {
// do something
return this;
}
};
})();
But so far I have notice that 0-2 examples have the best capabilities to be extended and can adapt better OOP rules.
Which of the following can serve as Class constructor and why?
This is one of my major issues. I can't clearly figure the best structure for a class constructor. The problems gets worse when it comes to extend a class ( and use it as a super/parent constructor )
The following code is my example of use. My experience has show me the 6th(5) example is the best to use when it comes to flexibility inside the "Class". But the inheritance is still tricky.
//5.example
var F = new function(a, b, c) {
var x = 0;
F.prototype.init = function(a, b, c) {
// do something
return this;
};
// During runtime will compute & initilize
return this.init(a, b, c);
};
//6.example
function G(a, b, c) {
var x;
var y;
function init() {
x = a;
y = b + c;
return this;
};
return this.init();
};
//7.example
var H = new function(a, b, c) {
var instance = { // Runtime Construction
x: a,
y: b + c,
};
// do something
return init;
};
Is it possible to achieve extension and inheritance as it happens in any common OOP language?
I have tried various techniques but none have convince me to be the optimal.
//8.example
var I = new F.prototype;
I.prototype.ifunc() {
// do something
return this;
}
//9.example
var J = new G(0,1,2);
J.jfunc() {
// do something
return this;
}
So to sum up, What is the best practice to write OO JS? and how can you benchmark it to reject others?