我想在Javascript中实现一个集合 - 有无论如何实现我的集合中的元素数组索引器?如何在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
反正有没有做到这一点?
你不能。任何具体的原因你不只是使用'数组'? – jbabey
我认为你的代码中缺少一些东西。 'collection'永远不会被填充,所以没有Array原型被复制。你可以发布一个工作小提琴吗? – David