Javascript - 私有数组

时间:2015-02-16 13:27:16

标签: javascript node.js

我在javascript中非常简单地挣扎。我想要一个只能通过对象的方法修改的数组。请考虑以下示例:

var Cart = function() {
    this.items = [];
}

Cart.prototype.getItems = function() {
    return this.items;
}

Cart.prototype.addItem = function(item) {
    this.items.push(item);
}

module.exports = Cart;

我希望能够通过addItem方法添加新项目,并通过getItems方法检索项目。我不希望能够以Cart.items.push(item)为例。

我怎样才能实现这个目标?

4 个答案:

答案 0 :(得分:1)

使用ES6 WeakMap,您可以这样做:

var items = new WeakMap();

var Cart = function() {
  items[this] = [];
};

Cart.prototype.getItems = function() {
  return items[this];
};

Cart.prototype.addItem = function(item) {
  items[this].push(item);
};

module.exports = Cart;

答案 1 :(得分:0)

在javascript中,您不拥有私人财产。以下是一些选项:

1 - 调用属性_items。这是一个众所周知的命名私有财产的惯例;

2 - 使用闭包:

var Cart = function() {
  var items = [];

  this.getItems = function() {
    return items;
  };

 this.addItem = function(item) {
    items.push(item);
 };    

}

3 - 使用符号。它们不是真正的私人,但很难发现:

var items = Symbol();
var Cart = function() {
    this[items] = [];
}

Cart.prototype.getItems = function() {
    return this[items];
}

Cart.prototype.addItem = function(item) {
    this[items].push(item);
}

4 - 改为使用private-symbol模块。这只适用于node.js / io.js(使用v8 C ++ API),但为您提供真正的私有符号

5 - 使用WeakMap

var items = new WeakMap();
var Cart = function() {
    items.set(this, []);
}

Cart.prototype.getItems = function() {
    return items.get(this);
}

Cart.prototype.addItem = function(item) {
    items.get(this).push(item);
}

答案 2 :(得分:-1)

这是否符合您的要求?

var Cart = function() {
    var items = [];

    this.getItems = function() {
        return items;
    };

    this.addItem = function(item) {
        items.push(item);
    };
}

答案 3 :(得分:-2)

您可以通过利用构造函数的scope来实现该功能。

不是将数组定义为公共属性,而是将其定义为变量:

var Cart = function() {
    var items = [];

    this.getItems = function() {
        return items;
    }

    this.addItem = function(item) {
        items.push(item);
    }

    this.addAndRetrieve = function(item) {
        items.push(item);
        return items;
    }
}

module.exports = Cart;

然后,您可以通过公开的方法getItemsaddItem

访问它
var x = new Cart(),
    y = new Cart();

x.addItem(1);
y.addItem(2);

x.getItems(); // [1]
y.getItems(); // [2]

EDIT1 :如果这些是您想要在实例上链接的唯一两种方法,您只需将它们组合在一个新功能中即可实现组合功能。

相关问题