【发布时间】:2016-03-25 06:04:23
【问题描述】:
我想为类以及类实例创建设置一个设计标准。结合来自多个网站的大量英特尔(例如来自 stackoverflow),终于有一种方法可以相对最大的灵活性。我的目标正是让代码结构的行为类似于更多定义的 Java 类等。
这是我目前所拥有的工作代码n-p(包括解释):
var MyClass = function (prop1)
{
var _class = MyClass;
var _proto = _class.prototype;
// public member of constructed class-instance
this.prop1 = prop1;
// private static property as well as private member of class-instances
// (see getter below!)
var prop2 = this.prop1 * 10;
// need to use this. instead of _proto because the property prop2 of
// the class itself would be returned otherwise
this.getProp2 = function ()
{
return prop2;
}
// 1 function for all instances of the class
// reached by a fallback to the prototype
_proto.protoAlert = function ()
{
// must call this.getProp2() instead of using prop2 directly
// because it would use the private static member of the class
// itself instead the one of the class-instance
alert(this.prop1 + " " + this.getProp2());
}
};
var c1 = new MyClass(1);
c1.protoAlert();
var c2 = new MyClass(2);
c2.protoAlert();
c1.protoAlert();
到目前为止效果很好。但是,要避免引发脚本错误和未发现的不当行为,需要采取一些障碍。私有属性prop2 存在于类和类实例中。这可能是一个无意的双重身份。此外,类实例的私有属性只能通过 setter 和 getter 函数正确访问。这并不是最糟糕的事情,因为它强制使用一种通用的方式来访问私有变量。缺点是:必须使用 this. 调用 Setter 和 getter 才能实际引用类实例的 prop2 然后返回它。至于类继承——我还没有按照我目前的标准来研究这个话题。希望它也能成功。
有没有更优雅的解决方案,或者至少有一个不太容易出错的解决方案?
提前谢谢你!
【问题讨论】:
-
个人意见:更优雅的解决方案是根本不使用类。在 javascript 中,组合优于继承。另外,如果你想要优雅,请参阅 bergis 评论,不要在类中声明原型,这是自找麻烦。
-
你为什么不使用已建立的
MyClass.prototype.protoAlert = function ..方法(在构造函数之外!),而是在严重地重新发明轮子......?! -
here you go,完成了模块化、封装和继承。或者现在只使用 ES6
class语法。 -
“私有属性
prop2存在于类和类实例中” – 什么?不清楚这意味着什么或你是如何得出这个结论的。
标签: javascript class instance private