跨浏览器的方式来子类JavaScript Array并获取array[i]方法

Cross-browser way to subclass JavaScript Array and get the array[i] method?

本文关键字:array 获取 方法 Array 浏览器 方式 JavaScript 子类      更新时间:2023-09-26

很高兴得知这种基本上子类化JavaScript Array(从链接复制的代码)的方法:

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]

但这还不完全完整。 有没有办法像这样伪造数组的子类获取[]方法?

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

这样,在执行 for 循环时,您仍然可以将其视为数组:

for (var i = 0; i < s.length; i++) {
  var item = s[i];
}
仅适用于

带有__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

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

我发现子类化"数组"的最佳方法不是子类化"数组",而是另一个"数组类对象",那里有很多,一种是使用集合。基本上,它完成了数组所做的一切(包括括号表示法),但是一个"自定义"原型,因此它可以很容易地被子类化,不像原生原型,原生原型在子类化时经常有问题。

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();