我可以帮您翻译成中文。这段内容是关于JavaScript集合实现的问题,是否有办法为集合中的元素实现类似于数组的索引器?
目前,我有以下代码:
但是我无法弄清楚如何使以下内容正常工作:
有没有什么方法可以做到这一点?
目前,我有以下代码:
var Collection = function() {
var collection = [];
var addAccessor = function(api, name) {
if (toString.call(collection[name]) == '[object Function]') {
api[name] = (function(){
return function () {
return collection[name](arguments);
};
}());
}
else {
Object.defineProperty(api, name, {
get: function() { return collection.length; },
enumerable: true,
configurable: true
});
}
};
var publicApi = {};
var methods = Object.getOwnPropertyNames(Array.prototype);
for(var i = 0, len = methods.length; i < len; ++i) {
var method = methods[i];
addAccessor(publicApi, method);
}
return publicApi;
};
};
所有Array.prototype
的方法和属性都按预期工作。
var c = Collection();
c.push(4);
console.log(c.length); // 1
但是我无法弄清楚如何使以下内容正常工作:
console.log(c[0]); // should print 4, currently undefined
有没有什么方法可以做到这一点?
collection
从未被填充,因此没有复制任何数组原型。你能发布一个可工作的fiddle吗? - David Hellsing