我知道这是一个老话题,但我试图找到一种方法来保持代码的“简单性”的可维护性的目的,并保持轻的内存负载。它有这样的模式。希望能有所帮助。
const PublicClass=function(priv,pub,ro){
let _priv=new PrivateClass(priv,pub,ro);
['publicMethod'].forEach(k=>this[k]=(...args)=>_priv[k](...args));
['publicVar'].forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k],set:v=>_priv[k]=v}));
['readOnlyVar'].forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k]}));
};
class PrivateClass{
constructor(priv,pub,ro){
this.privateVar=priv;
this.publicVar=pub;
this.readOnlyVar=ro;
}
publicMethod(arg1,arg2){
return this.privateMethod(arg1,arg2);
}
privateMethod(arg1,arg2){
return arg1+''+arg2;
}
}
// in node;
module.exports=PublicClass;
// in browser;
const PublicClass=(function(){
// code here
return PublicClass;
})();
同样的原则适用于老式浏览器:
var PublicClass=function(priv,pub,ro){
var scope=this;
var _priv=new PrivateClass(priv,pub,ro);
['publicMethod'].forEach(function(k){
scope[k]=function(){return _priv[k].apply(_priv,arguments)};
});
['publicVar'].forEach(function(k){
Object.defineProperty(scope,k,{get:function(){return _priv[k]},set:function(v){_priv[k]=v}});
});
['readOnlyVar'].forEach(function(k){
Object.defineProperty(scope,k,{get:function(){return _priv[k]}});
});
};
var PrivateClass=function(priv,pub,ro){
this.privateVar=priv;
this.publicVar=pub;
this.readOnlyVar=ro;
};
PrivateClass.prototype.publicMethod=function(arg1,arg2){
return this.privateMethod(arg1,arg2);
};
PrivateClass.prototype.privateMethod=function(arg1,arg2){
return arg1+''+arg2;
};
为了减轻公共类的冗长和负载,将此模式应用于构造函数:
const AbstractPublicClass=function(instanciate,inherit){
let _priv=instanciate();
inherit.methods?.forEach(k=>this[k]=(...args)=>_priv[k](...args));
inherit.vars?.forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k],set:v=>_priv[k]=v}));
inherit.readonly?.forEach(k=>Object.defineProperty(this,k,{get:()=>_priv[k]}));
};
AbstractPublicClass.static=function(_pub,_priv,inherit){
inherit.methods?.forEach(k=>_pub[k]=(...args)=>_priv[k](...args));
inherit.vars?.forEach(k=>Object.defineProperty(_pub,k,{get:()=>_priv[k],set:v=>_priv[k]=v}));
inherit.readonly?.forEach(k=>Object.defineProperty(_pub,k,{get:()=>_priv[k]}));
};
使用:
// PrivateClass ...
PrivateClass.staticVar='zog';
PrivateClass.staticMethod=function(){return 'hello '+this.staticVar;};
const PublicClass=function(priv,pub,ro){
AbstractPublicClass.apply(this,[()=>new PrivateClass(priv,pub,ro),{
methods:['publicMethod'],
vars:['publicVar'],
readonly:['readOnlyVar']
}]);
};
AbstractPublicClass.static(PublicClass,PrivateClass,{
methods:['staticMethod'],
vars:['staticVar']
});
PS:这种方法的默认(大多数时候可以忽略不计)是,与完全公共相比,它可以占用很小的计算负载。但只要你不使用它与高度请求类应该是可以的。