我道歉,因为这个话题出现了很多,但我还没有能够在今天读到的任何内容中充分解释这个问题.
我正在尝试创建一个简单的集合类(并同时学习javascript原型),用于存储具有"name"属性的对象,并允许其成员通过索引或值访问.到目前为止,我有这个:
function Collection() {}
Collection.prototype.constructor = Collection;
Collection.prototype._innerList = [];
Collection.prototype._xref = {};
Collection.prototype.count = function () { return this._innerList.length; };
Collection.prototype.add = function (obj) {
this._xref[obj.name] = this._innerList.push(obj) - 1;
}
Collection.prototype.get = function (id) {
if (typeof id == "string") {
return this._innerList[this._xref[id]];
} else {
return this._innerList[id];
}
};
Run Code Online (Sandbox Code Playgroud)
问题:
var foo = new Collection();
foo.add({name: "someitem", value:"hello world"}); // foo.count()== 1
var bar= new Collection();
bar.add({name: "someotheritem", value:"hello world"}); // bar.count()== 2
Run Code Online (Sandbox Code Playgroud)
嗯...
基本上, …