javascript定義類的幾種方法

來源:互聯網
上載者:User

 /*<br />  工廠方式--- 建立並返回特定類型的對象的 工廠函數 ( factory function )<br />  */ <br />function createCar(color,doors,mpg){  <br />   var tempCar = new Object;  <br />   tempCar.color = color;  <br />   tempCar.doors = doors;  <br />   tempCar.mpg = mpg;  <br />   tempCar.showCar = function(){  <br />     alert(this.color + " " + this.doors);  <br />   }  <br />  return tempCar;  <br />} <br />  /*<br />  建構函式方式--- 建構函式看起來很像工廠函數<br />  */ <br />function Car(color,doors,mpg){  <br />  this.color = color;  <br />  this.doors = doors;  <br />  this.mpg = mpg;  <br />  this.showCar = function(){  <br />     alert(this.color);  <br />   };  <br />} <br />  /*<br />  原型方式--- 利用了對象的 prototype 屬性,可把它看成建立新對象所依賴的原型<br />  */ <br />function Car(color,doors,mpg){  <br />  this.color = color;  <br />  this.doors = doors;  <br />  this.mpg = mpg;  <br />  this.drivers = new Array("nomad","angel");  <br />}  <br />Car.prototype.showCar3 = function(){  <br />   alert(this.color);  <br />};<br />  /*<br />  混合的建構函式 /原型方式--- 用建構函式定義對象的所有非函數屬性,用原型方式定義對象的函數屬性(方法)<br />  */ <br />function Car(sColor, iDoors, iMpg) {  <br />  this.color = sColor;  <br />  this.doors = iDoors;  <br />  this.mpg = iMpg;  <br />  this.drivers = new Array("Mike", "Sue");  <br />}  <br />Car.prototype.showColor = function () {  <br />   alert(this.color);  <br />}; <br />  /*<br />  動態原型方法--- 在建構函式內定義非函數屬性,而函數屬性則利用原型屬性定義。唯一的區別是賦予對象方法的位置。<br />  */ <br />function Car(sColor, iDoors, iMpg) {  <br />  this.color = sColor;  <br />  this.doors = iDoors;  <br />  this.mpg = iMpg;  <br />  this.drivers = new Array("Mike", "Sue");  <br />  if (typeof Car._initialized == "undefined") {  <br />     Car.prototype.showColor = function () {  <br />       alert(this.color);  <br />     };  <br />     Car._initialized = true;  <br />   }  <br />}<br />  //該方法使用標誌( _initialized )來判斷是否已給原型賦予了任何方法。  <br />  利用原型prototype。<br />function Bar(text, url) {<br />this.text = text;<br />this.url = url;<br />}<br />Bar.prototype = {<br />render : function() {<br />document.write('<a href="' + this.url + '" mce_href="' + this.url + '">' + this.text + '</a>');<br />

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.