简体   繁体   中英

How to implement an array-like indexer ([ ]) in Javascript?

I'm trying to implement a collection in Javascript - is there anyway to implement an array-like indexer for elements in my collection?

So far, I have the following code:

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;
  };
};

All of the Array.prototype methods and properties work as expected.

var c = Collection();
c.push(4);
console.log(c.length);  // 1

But the one thing I can't figure out is how to get the following to work:

console.log(c[0]);     // should print 4, currently undefined

Is there anyway to do this?

If you want to "extend" Array, the classic way would be something like:

function Collection(){};
Collection.prototype = new Array();
Collection.constructor = Collection;

Now add your own methods:

Collection.prototype.color = function() {
    this.push('color');
};

And use it with new :

var myArray = new Collection();
myArray.push(1);
myArray.color();

If you want to add a new push method that access Array push, try:

Collection.prototype.push = function() {
    console.log('pushed!');
    Array.prototype.push.apply(this, [].slice.call(arguments));
};

using classes:

class Collection extends Array {
  color() {
    this.push('color')
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM