javascript - 对于类实例的私有(private)成员是否有更优雅的方法?

标签 javascript class instance private

我想为类以及类实例创建制定一个设计标准。结合来自多个网站(例如来自 stackoverflow)的大量信息,最终找到了一种具有相对最大灵 active 的方法。我的目标正是使代码结构的行为类似于更定义的 Java 类等。

这是我迄今为止所拥有的工作代码片段(包括解释):

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();

到目前为止效果很好。然而,为了不引发错误和未被发现的脚本不当行为,需要采取一些障碍。私有(private)属性 prop2 存在于类和类实例中。这可能是无意的双重身份。此外,类实例的私有(private)属性只能通过 setter 和 getter 函数正确访问。这还不是最糟糕的事情,因为它强制采用一种通用的方式来访问私有(private)变量。缺点是:必须使用 this. 调用 Setter 和 getter,才能实际引用类实例的 prop2,然后返回它。至于类继承 - 我还没有用我当前的标准研究这个主题。希望它也会成功。

是否有一种更优雅的解决方案,或者至少是一种不太容易出现错误的解决方案?

提前谢谢您!

最佳答案

JavaScript 并没有真正为私有(private)属性提供实用的模式。仅当您在构造函数中定义所有方法时,您使用的模式才有效。您应该记住,这意味着每次创建类时,都会创建所有方法。

如果你想一想,私有(private)变量在程序中不提供任何功能它们为程序员服务,让程序员记住他应该做什么以及他应该做什么不会改变。因此,您可以简单地使用一些命名模式。我在其他人的代码中经常看到这样的情况:

function MyClass() {
    // Private property
    this._helloWord = "Hello word.";
}
// From outside, accessed as `helloWord`, without underscore
Object.defineProperty(MyClass.prototype, "helloWord", {
    get: function() {console.log("helloWord getter");return this._helloWord;},
    set: function(value) {console.log("helloWord setter");return this._helloWord = value;},
};
MyClass.prototype.alertProp = function() {
    alert(this._helloWord);
}
// Accessing from the outside:
var instance = new MyClass();
alert(instance.helloWord); // will activate the getter function

大多数人会立即明白 _underscored 变量有一些特殊之处。您还可以通过这种方式使变量常量:

Object.defineProperty(MyClass.prototype, "helloWord", {
    value: "Hello world",
    writable: false // <----
};

详细了解Object.defineProperty 。您还应该了解 Javascript 的结构与 OOP 语言的结构略有不同。如果您尝试将其他语言的模式推到其上,则会导致性能和结构问题。

关于javascript - 对于类实例的私有(private)成员是否有更优雅的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34357148/

相关文章:

C++ 访问静态 constexpr 数组

c# - 将 Firefox 嵌入到 .NET 控件中

java - 基于另一个类创建一个类的实例

c# - 静态变量实例和 AppDomains,发生了什么?

javascript - 一些文本在被 JS 函数更改时会变形

javascript - 为什么按空格键时不显示警报?

php - 我无法将值传递给 uploadify scriptData

javascript - 当可见性改变时,IFrame 滚动条在 chrome 上消失

c++ - 我是否必须将非标准库包含到 C++ 中的类定义中?

java - 获取 JAR 文件的位置