2010-06-21 89 views
2

在JavaScript的本機類型(如Array,String,Number等)中創建附加功能的原型是一個壞主意嗎?原型JavaScript原生類型,氣餒?

我認爲擁有像myArr.pop()等功能會很棒,但如果某一天成爲ECMAScript x的一部分,並且與我的實現不同,那麼它可能會破壞整個軟件?

+2

負責原型框架的人不這麼認爲。 – Pointy 2010-06-21 14:12:48

+0

如果無法完成,他們不會讓你。 – 2010-06-21 14:37:38

回答

4

Prototype是一個廣泛擴展原生Javascript類型和DOM類的庫,並且非常好地展示了擴展Javascript本地類型的好,壞和醜。

好:你得到自然的Javascript代碼。

不好:你忘了你實際上在使用Prototype - 當你切換到一個不使用Prototype的項目時會產生混淆。 (爲什麼我不能......哦,對,這是一個Prototype功能。)

醜陋:如果由於衝突庫而導致方法定義(兩個方法在契約或簽名中不同)有衝突,瀏覽器或規範,您可能必須修改客戶端代碼以保持兼容性。這使得在一個已經困擾他們的世界中再考慮一個兼容性問題。爲了兼容性和保持我自己的想法清晰起見,我個人不要擴展本地或DOM的JavaScript類型,並且選擇較少侵入性的庫到Prototype。

但是,如果您對這些缺點感到放心,不要讓我阻止您。

2

如果您試圖複製爲某些瀏覽器而不是其他瀏覽器定義的方法,請嘗試使定義與本機實現相匹配。

if(![].indexOf){ 
    Array.prototype.indexOf= function indexOf(what, i){ 
     i= i || 0; 
     var L= this.length; 
     while(i< L){ 
      if(this[i]=== what) return i; 
      ++i; 
     } 
     return -1; 
    } 
} 
if(![].map){ 
    Array.prototype.map= function map(fun, scope){ 
     var L= this.length, A= Array(this.length), i= 0, val; 
     if(typeof fun== 'function'){ 
      while(i< L){ 
       if(i in this){ 
        A[i]= fun.call(scope, this[i], i, this); 
       } 
       ++i; 
      } 
      return A; 
     } 
     else throw 'missing function argument'; 
    } 
} 
if(!''.trim){ 
    String.prototype.trim= function trim(){ 
     return this.replace(/^\s+|\s+$/g,''); 
    } 
} 

如果可能,將使用本地方法。 如果你滾你自己的方法,儘量給他們一個名字,是不是可能被捷足先登

我想有一個洗牌和數組一個naturalSort方法, 但我給他們稍微偏離節拍名。

Array.prototype.a1Sort= function(){ 
    var a, b, a1, b1, rx= /(\d+)|(\D+)/g, rd= /\d+/; 
    return this.sort(function(as, bs){ 
     a= String(as).toLowerCase().match(rx); 
     b= String(bs).toLowerCase().match(rx); 
     while(a.length && b.length){ 
      a1= a.shift(); 
      b1= b.shift(); 
      if(rd.test(a1) || rd.test(b1)){ 
       if(!rd.test(a1)) return 1; 
       if(!rd.test(b1)) return -1; 
       if(a1!= b1) return a1 - b1; 
      } 
      else if(a1!= b1) return a1> b1? 1: -1; 
     } 
     return a.length - b.length; 
    }); 
} 
Array.prototype.disorder= function(force){ 
    var i, temp, L= this.length, A= force? this: this.concat(); 
    while(--L){ 
     i= Math.floor(Math.random()*L); 
     temp= A[i]; 
     A[i]= A[L]; 
     A[L]= temp; 
    } 
    return A; 
} 

如果添加到原型,請務必將其記錄下來,並在使用他們 - 是否有人曾經打算用你的代碼工作,包括你每一個腳本引用文檔。