[JavaScript]擴充方法

[JavaScript]擴充方法

為某個型別擴充方法

   1:  Array.prototype.lookup = function(obj) {
   2:      // TODO
   3:  }

為某個物件擴充方法, 如果重新new 一個物件, JavaScript是依照型別去建立, 故事先訂義之擴充方法, 將全數消失

   1:      var array = [];
   2:      array.lookup = function(){ return true;}
   3:      
   4:      alert(array.lookup());
   5:      
   6:      array = [];
   7:      alert(array.lookup()); // Exception
   1:      // 陣列宣告    , 並給予物件擴充方法
   2:      var array = [];
   3:      array.lookup = function(){ return true;}    
   4:      document.write("array.lookup is defined? " + (array.lookup != undefined ) + "<br />");
   5:      // 陣列重新宣告, 原物件擴充方法消失
   6:      array = [];
   7:      document.write("Re-array().lookup is defined? " + (array.lookup != undefined ) + "<br /><br />");
   8:      
   9:      // 名稱空間宣告, 並給予物件擴充方法
  10:      var classA = {};    
  11:      classA.lookup = function() { return true; }
  12:      document.write("classA.lookup is defined? " + (classA.lookup != undefined ) + "<br />");    
  13:      // 名稱空間重新宣告, 原物件擴充方法消失
  14:      classA = {};    
  15:      document.write("Re-classA().lookup is defined? " + (classA.lookup != undefined ) + "<br /><br />");
  16:      
  17:      // 類別宣告-Type 1
  18:      var classB = function(){
  19:          this.lookup = function(){ return true; } // 用this來增加function        
  20:      };    
  21:      document.write("classB() is defined? " + (classB() != undefined) + "<br />" ); // 不可將類別當方法來使用
  22:      var classb = new classB();    
  23:      document.write("new classB().lookup is defined? " + (classb.lookup != undefined ) + "<br /><br />");
  24:      
  25:      // 類別宣告-Type 2
  26:      var classC = function(){
  27:          return { // 用return new 來增加function 
  28:              lookup: function(){ return true;} 
  29:          }
  30:      }
  31:      document.write("classC() is defined? " + (classC() != undefined ) + "<br />" );;    
  32:      var classc = classC();
  33:      document.write("classC().lookup is defined? " + (classc.lookup != undefined ) + "<br />");
  34:      var classc_2 = new classC(); // also do it
  35:      document.write("new classC().lookup is defined? " + (classc_2.lookup != undefined ) + "<br />");
  36:      document.write("classc 1 and 2 are different? " + ( classc != classc_2 ) + "<br /><br />");

 

結果

   1:  array.lookup is defined? true
   2:  Re-array().lookup is defined? false
   3:   
   4:  classA.lookup is defined? true
   5:  Re-classA().lookup is defined? false
   6:   
   7:  classB() is defined? false
   8:  new classB().lookup is defined? true
   9:   
  10:  classC() is defined? true
  11:  classC().lookup is defined? true
  12:  new classC().lookup is defined? true
  13:  classc 1 and 2 are different? true

 

結論: 弱型別的語言, 很容易因為宣告而發生非預期的異常, 要多熟悉宣告的方式, 並一統自己延伸套件的宣告方式, 才能儘量避免異常.