2017-03-31 48 views
1

我创建了一个基于这个article的集合。我发现它运行在chrome,firefox和ie9 +上。 我认为有些事情不会起作用,或者,ie10模拟器对于Windows 10并不能给我真实的图像。创建扩展本地数组的集合有什么危险?

这个扩展会出现什么问题?

测试代码:

<script> 
    function Collection() { 
     var collection = Object.create(Array.prototype); 

     collection = (Array.apply(collection, arguments) || collection); 


     return collection; 
    } 

    Collection.prototype = Object.create(Array.prototype); 

    var collection = new Collection(); 

    collection[0] = 1; 

    console.log(collection[0]); 
</script> 

回答

1

看一看http://perfectionkills.com/how-ecmascript-5-still-does-not-allow-to-subclass-an-array/

特别地,

var collection = Object.create(Array.prototype); 

创建并从Array.prototypeCollection.prototype继承的对象。它创建一个对象,而不是一个数组。

collection = (Array.apply(collection, arguments) … 

Array忽略其this值。并创建一个Array实例,而不是一个Collection之一。

… || collection) 

这是毫无意义的,因为Array永远没有返回falsy值,所以collection简直就是总是被忽略。

这个扩展会出现什么问题?

它创建Array s,而不是Collection s。根本没有扩展。尝试在Collection.prototype上添加一些方法并调用它们。

+0

另一个重点:'collection.push('hello'); collection.length = 0;集合[0]; //'你好'。 – Kaiido

+0

@Kaiido当它是一个对象而不是数组时,是的。 – Bergi