【问题标题】:Cross-browser way to subclass JavaScript Array and get the array[i] method?跨浏览器继承 JavaScript Array 并获取 array[i] 方法?
【发布时间】:2012-06-01 13:29:05
【问题描述】:

很高兴得知 this way 基本上继承了 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]

但这并不完全。有没有办法像这样伪造 Array 的子类获得[] 方法?

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

【问题讨论】:

  • 这是一个问题...我认为没有跨浏览器的方法可以解决它。我想到了两件事:1. 属性 - 不是真正的跨浏览器 2. 只需强制执行 .push,这可行 - 如果可能的话。
  • 为什么还需要对数组进行子类化?您可以创建一个数组并仍然为其附加新属性。

标签: javascript arrays browser subclass


【解决方案1】:

仅适用于带有__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

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

【讨论】:

    【解决方案2】:

    我发现对“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();
    

    【讨论】:

      猜你喜欢
      • 2017-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多