使用新方法对Array Class进行原型设计的最佳方法是什么?

Mar*_*wan 2 javascript javascript-framework

我有许多功能方法我需要使用它,我需要发布一个使用这种方法的库与JavaScript开发人员分享它非常有用,所以例如我需要添加一个名为的方法duplicates 将返回给我的数组的重复项你可以看到ECMA没有正式发布这个方法所以我不知道放置脚本的最佳形式

1-

      Array.prototype.duplicate = function (){
        //script here its usefull to use `this` refer to the Array
       }
Run Code Online (Sandbox Code Playgroud)

使用它就像

[1,2,2].duplicates();
Run Code Online (Sandbox Code Playgroud)

2-

 var Ary = function(a){
      if(!(this instanceOf Ary))
          return new Ary(a)
      if(Object.prototype.toString.call(a) != '[object Array]')
          return new Error(a + 'is not an Array')
      else
      {
          for(var i =0 ; i<a.length; i++)
          {
             this.push(a[i]);
          }


      }
   }
Ary.prototype = new Array();
Ary.prototype.constructor = Ary; 

Ary.prototype.duplicates = function(){ 
   //script here its usefull to use `this` refer to the Array
};
Run Code Online (Sandbox Code Playgroud)

使用它就像

Ary([1,2,2]).duplicates();
Run Code Online (Sandbox Code Playgroud)

我需要知道是不是更直接使用原型到Array JavaScript Class来添加功能,如果它没有官方发布ECMA而是我们继承Array Class然后玩它?

或者它可以做原型吗?

以及后果

问候

T.J*_*der 6

对于你自己的代码,可以添加一个duplicates方法,Array.prototype但是如果你使用错误地用于for..in循环遍历数组的代码(你自己或你正在使用的代码),你需要为可能发生的事情做好准备:

for (var i in myArray) { // <==== Wrong without safeguards
}
Run Code Online (Sandbox Code Playgroud)

...因为i"duplicates"在某个时刻获得值,因为for..in循环遍历对象及其原型的可枚举属性,它不会循环遍历数组索引.for..in如果你正确处理它,可以在数组上使用,在SO的其他答案中更多.

如果您只是在支持ES5的环境(现代浏览器,而不是IE8及更早版本)中工作,您可以通过添加duplicatesvia 来避免这种情况Object.defineProperty,如下所示:

Object.defineProperty(Array.prototype, "duplicates", {
    value: function() {
        // ...the code for 'duplicates' here
    }
});
Run Code Online (Sandbox Code Playgroud)

定义为该方式的属性不可枚举,因此不会显示在for..in循环中,因此无法正确处理for..in数组的代码不会受到影响.

不幸的是,JavaScript目前无法从Array.prototype(第二个选项)正确派生,因为它对Array名称全部为数字的属性(称为"数组索引")和特殊length属性进行了特殊处理.目前,这些都不能在派生对象中正确提供.更多关于我的博客文章A Myth of Arrays中的特殊属性.