Eva*_*n P 6 javascript oop optimization
我正在努力优化我在JS中的实践,但我无法构建一个完美的基准来回答我以下问题.
JS"Class"的最佳结构是什么?
我已经尝试了以下各项,没有任何明显的性能峰值.
(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;
}
};
})();
Run Code Online (Sandbox Code Playgroud)
但到目前为止,我已经注意到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;
};
Run Code Online (Sandbox Code Playgroud)
是否有可能实现扩展和继承,因为它发生在任何常见的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;
}
Run Code Online (Sandbox Code Playgroud)
总结一下,编写OO JS的最佳实践是什么?你如何以它为基准来拒绝别人呢?