3

Very glad to learn of this way of basically subclassing a JavaScript Array (code copied from link):

function SomeType() {
    this.push(16);
}

SomeType.prototype = [];
SomeType.prototype.constructor = SomeType; // Make sure there are no unexpected results

console.log(new SomeType()); // Displays in console as [16]

But this isn't quite complete. Is there a way to fake subclass the Array like this and get the [] method?

var a = [];
a[3]  = true;
console.log(a.length); //=> 4

var s = new SomeType();
s[3]  = true;
console.log(s.length); //=> 1

This way you can still treat it as an array when doing a for loop:

for (var i = 0; i < s.length; i++) {
  var item = s[i];
}
4

2 回答 2

2

仅适用于带有__proto__(已弃用)的浏览器,因此它不是跨浏览器:

var CustomArray = function ( ) {
  var array = [ 16 ];
  array.__proto__ = this.__proto__;
  return array;
};

CustomArray.prototype = [];
CustomArray.prototype.constructor = CustomArray;

var array = new CustomArray( );
console.log( array instanceof Array );       // true
console.log( array instanceof CustomArray ); // true

array[ 3 ] = 42;
console.log( array.length );                 // 4

我认为没有其他方法可以做到这一点。

于 2012-05-29T14:57:39.370 回答
0

我发现对“Array”进行子类化的最佳方法不是子类化“Array”,而是另一个“Array-Like-Object”,其中有很多,其中一个是 Collection。基本上它完成了数组所做的所有事情(包括括号表示法),但它是一个“自定义”原型,因此它可以很容易地被子类化,这与原生原型不同,原生原型在子类化时通常会出现问题。

http://codepen.io/dustinpoissant/pen/AXbjxm?editors=0011

var MySubArray = function(){
  Collection.apply(this, arguments);
  this.myCustomMethod = function(){
    console.log("The second item is "+this[1]);
  };
};
MySubArray.prototype = Object.create(Collection.prototype);

var msa = new MySubArray("Hello", "World");
msa[2] = "Third Item";
console.log(msa);
msa.myCustomMethod();
于 2016-07-11T20:31:17.310 回答