? Java代碼
  1. /*?
  2. ???工廠方式---?創(chuàng)建并返回特定類型的對(duì)象的?工廠函數(shù)?(?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. ???構(gòu)造函數(shù)方式---?構(gòu)造函數(shù)看起來(lái)很像工廠函數(shù)??
  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. ???原型方式---?利用了對(duì)象的?prototype?屬性,可把它看成創(chuàng)建新對(duì)象所依賴的原型??
  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. ???混合的構(gòu)造函數(shù)?/原型方式---?用構(gòu)造函數(shù)定義對(duì)象的所有非函數(shù)屬性,用原型方式定義對(duì)象的函數(shù)屬性(方法)??
  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. ????動(dòng)態(tài)原型方法---?在構(gòu)造函數(shù)內(nèi)定義非函數(shù)屬性,而函數(shù)屬性則利用原型屬性定義。唯一的區(qū)別是賦予對(duì)象方法的位置。??
  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. }?//該方法使用標(biāo)志(?_initialized?)來(lái)判斷是否已給原型賦予了任何方法。