![](/img/trans.png)
[英]Implement Array-like behavior in JavaScript without using Array
[英]How to implement an array-like indexer ([ ]) in 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
有没有办法做到这一点?
如果你想“扩展”数组,经典的方法是这样的:
function Collection(){};
Collection.prototype = new Array();
Collection.constructor = Collection;
现在添加您自己的方法:
Collection.prototype.color = function() {
this.push('color');
};
并将其与new
一起使用:
var myArray = new Collection();
myArray.push(1);
myArray.color();
如果要添加访问数组推送的新push
方法,请尝试:
Collection.prototype.push = function() {
console.log('pushed!');
Array.prototype.push.apply(this, [].slice.call(arguments));
};
使用类:
class Collection extends Array {
color() {
this.push('color')
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.