我正在努力优化我在 JS 中的实践,但我无法构建一个完美的基准来回答我以下问题。
JS“类”的最佳结构是什么?
我已经尝试了以下各项,但没有任何明显的性能峰值。
(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;
}
};
})();
但到目前为止,我注意到 0-2 个示例具有最好的扩展能力,并且可以适应更好的 OOP 规则。
以下哪项可以作为类构造函数,为什么?
这是我的主要问题之一。我无法清楚地确定类构造函数的最佳结构。当涉及到扩展类(并将其用作超级/父构造函数)时,问题会变得更糟
以下代码是我的使用示例。我的经验告诉我,在“类”内部的灵活性方面,第 6 (5)个示例是最好使用的。但是继承仍然很棘手。
//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;
};
是否有可能像在任何常见的 OOP 语言中一样实现扩展和继承?
我尝试了各种技术,但没有一个能说服我成为最佳技术。
//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;
}
综上所述,编写 OO JS 的最佳实践是什么?以及您如何对其进行基准测试以拒绝其他人?