[JavaScript]類之二—javascript 類定義4種方法

來源:互聯網
上載者:User

javascript 類定義4種方法

 

Java代碼
  1. /*  
  2.    工廠方式--- 建立並返回特定類型的對象的 工廠函數 ( factory function )   
  3. */  
  4.     
  5.   
  6. function createCar(color,doors,mpg){   
  7.     var tempCar = new Object;   
  8.     tempCar.color = color;   
  9.     tempCar.doors = doors;   
  10.     tempCar.mpg = mpg;   
  11.     tempCar.showCar = function(){   
  12.         alert(this.color + " " + this.doors);   
  13.     }   
  14.     return tempCar;   
  15. }    
  16.   
  17. /*  
  18.    建構函式方式--- 建構函式看起來很像工廠函數   
  19. */  
  20. function Car(color,doors,mpg){   
  21.     this.color = color;   
  22.     this.doors = doors;   
  23.     this.mpg = mpg;   
  24.     this.showCar = function(){   
  25.         alert(this.color);   
  26.     };   
  27. }     
  28. /*  
  29.    原型方式--- 利用了對象的 prototype 屬性,可把它看成建立新對象所依賴的原型   
  30. */  
  31. function Car(color,doors,mpg){   
  32.     this.color = color;   
  33.     this.doors = doors;   
  34.     this.mpg = mpg;   
  35.     this.drivers = new Array("nomad","angel");   
  36. }   
  37.   
  38. Car.prototype.showCar3 = function(){   
  39.     alert(this.color);   
  40. };    
  41.   
  42. /*  
  43.    混合的建構函式 /原型方式--- 用建構函式定義對象的所有非函數屬性,用原型方式定義對象的函數屬性(方法)   
  44. */  
  45. function Car(sColor, iDoors, iMpg) {   
  46.     this.color = sColor;   
  47.     this.doors = iDoors;   
  48.     this.mpg = iMpg;   
  49.     this.drivers = new Array("Mike", "Sue");   
  50. }   
  51.   
  52. Car.prototype.showColor = function () {   
  53.     alert(this.color);   
  54. };     
  55. /*  
  56.     動態原型方法--- 在建構函式內定義非函數屬性,而函數屬性則利用原型屬性定義。唯一的區別是賦予對象方法的位置。   
  57. */  
  58. function Car(sColor, iDoors, iMpg) {   
  59.     this.color = sColor;   
  60.     this.doors = iDoors;   
  61.     this.mpg = iMpg;   
  62.     this.drivers = new Array("Mike", "Sue");   
  63.   
  64.     if (typeof Car._initialized == "undefined") {   
  65.   
  66.         Car.prototype.showColor = function () {   
  67.             alert(this.color);   
  68.         };   
  69.   
  70.         Car._initialized = true;   
  71.     }   
  72. } //該方法使用標誌( _initialized )來判斷是否已給原型賦予了任何方法。   
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.