【问题标题】:What is the best way to prototype Array Class with a new Methods使用新方法对 Array Class 进行原型设计的最佳方法是什么
【发布时间】:2013-01-10 09:09:02
【问题描述】:

我有许多需要使用的函数方法,我需要发布一个包含这些方法的库,以便与 JavaScript 开发人员共享它非常有帮助,例如我需要添加一个名为 duplicates 的方法将返回给我数组的副本 如您所见,ECMA 并未正式发布此方法,因此我不知道放置脚本的最佳形式

1-

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

像这样使用它

[1,2,2].duplicates();

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

像这样使用它

Ary([1,2,2]).duplicates();

我需要知道,如果它不是由 ECMA 官方发布的,而是我们从 Array 类继承然后使用它,是否更喜欢直接使用原型到 Array JavaScript 类来添加功能?

或者它可以做原型吗??

后果是什么

问候

【问题讨论】:

标签: javascript javascript-framework


【解决方案1】:

对于您自己的代码,可以将duplicates 方法添加到Array.prototype,但您确实需要为如果您使用错误的代码(您自己的代码或您正在使用的代码)可能会发生的情况做好准备使用for..in 循环遍历这样的数组:

for (var i in myArray) { // <==== Wrong without safeguards
}

...因为i 会在某个时候获得"duplicates" 的值,因为for..in 循环遍历对象及其原型的可枚举属性,所以它不会遍历数组索引。如果处理得当,可以在数组上使用for..in,在this other answer on SO 中使用更多。

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

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

以这种方式定义的属性不可枚举,因此不会出现在 for..in 循环中,因此无法正确处理数组上的 for..in 的代码不会受到影响。

不幸的是,目前在 JavaScript 中不可能正确地从 Array.prototype(您的第二个选项)派生,因为 Array 对名称全为数字的属性(称为“数组索引”)和一个特殊的 length 进行了特殊处理财产。目前,这些都不能在派生对象中正确提供。有关这些特殊属性的更多信息,请参阅我的博客文章 A Myth of Arrays

【讨论】:

    【解决方案2】:

    作为一般规则:不要修改原生 Javascript 对象原型。它可能看起来无害,但如果您在网站/应用程序中包含第三方代码,则可能会导致各种细微的错误。

    修改Array 原型特别邪恶,因为互联网上充斥着使用for ... in 构造迭代数组的错误代码。

    检查一下:

    for(var i in [1,2,3]) {
        console.log(i);
    }
    

    输出:

    1
    2
    3
    

    但是如果你修改了Array原型如下:

    Array.prototype.duplicates = function() { }
    

    输出

    1
    2
    3
    duplicates
    

    See for yourself.

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-20
      • 2018-05-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 2011-03-25
      相关资源
      最近更新 更多