javascript - 我应该如何操作具有相同原型(prototype)的另一个对象的 "private"成员?

标签 javascript oop functional-programming

在像 Java 这样基于类的语言中,我有时会利用类的私有(private)成员可以被同一类的其他对象访问的事实。例如,

class BitSet {
    private int[] words;

    public void and(BitSet set) {
        for (int i = 0; i < words.length; i++)
            words[i] &= (i < set.words.length) ? set.words[i] : 0; 
    }
}

现在,我正在使用构造函数模式使用 JavaScript 来创建“私有(private)”成员:

function BitSet() {
    var words = [];

    this.and = function (set) {
        // This is roughly what I'm trying to achieve.
        for (i = 0; i < words.length; i++)
             words[i] &= (i < set.words.length) ? set.words[i] : 0;
    }

    // This would solve the problem,
    // but exposes the implementation of the object and
    // clutters up the API for the user

    this.getWord = function(index) {
        return words[index];
    }
}

我知道我可能应该以不同的方式处理这个问题(而不是那么面向对象)。有人有更好的模式建议吗?

最佳答案

JavaScript是一种原型(prototype)的面向对象编程语言,而不是经典的面向对象编程语言。 JavaScript 中没有类,但您可以将原型(prototype)建模为类,因为 prototype-class isomorphism :

function CLASS(prototype) {
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

CLASS 函数允许您创建看起来像类的原型(prototype)。然而它们不是类。与其他语言中的类不同,JavaScript 中的原型(prototype)没有访问说明符。一切都必须是公开的或 hidden inside closures :

var BitSet = CLASS({
    constructor: function () {
        this.words = [];
    },
    and: function (set) {
        var length = this.words.length, setWords = set.words;
        for (var i = 0; i < length; i++) this.words[i] &= setWords[i] || 0;
    }
});

事实上,JavaScript 没有类或访问说明符是一件好事,因为您确实不需要它们。想一想。在 Java 等语言中,您真的需要访问说明符吗?如果一切都是公开的,真的会产生这么大的影响吗?以我的拙见,不会。

有些人认为公开所有内容是不好的,因为它会暴露实现细节并不必要地使用户 API 困惑。不对。只是不要记录那些您希望保密的属性。如果用户不需要了解某个属性,那么就不要记录它。

如果出于安全目的需要将变量设为私有(private),则 JavaScript 具有闭包。无论如何,此类属性不应被其他对象(即使是同一类的)访问。因此,不应该出现这样的情况:您需要将变量保持为私有(private)并使其也可供其他对象类访问。

最后,公开属性(property)有很多优点:

  1. 由于该属性是公共(public)的,因此您无需在构造函数内创建闭包。
  2. 可以在原型(prototype)上共享方法。因此该类的所有实例都共享方法。
  3. 您可以将对象初始化与对象方法分开。
  4. 代码更具可读性和可维护性。
  5. 对象创建速度更快。

关于javascript - 我应该如何操作具有相同原型(prototype)的另一个对象的 "private"成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19282434/

相关文章:

javascript - "map of union type values to strings"的 typescript 类型?

c++ - 多重虚继承

ruby - 如何传递函数而不是 block

c# - 挑战: Neater way of currying or partially applying C#4's string.加入

javascript - javascript中的concat函数?

javascript - 在 div 列表中的随机位置插入一个 div

c# - 类设计 - 从 <Object> 返回列表 <Object>

java - 常量类的接口(interface)模式

macros - Clojure 宏在调用时抛出 "CompilerException java.lang.IllegalStateException: Var clojure.core/unquote is unbound"

javascript - Server.listeners 不是函数