? 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?)來判斷是否已給原型賦予了任何方法。