javascript 裡的類實現

來源:互聯網
上載者:User
摘抄自《javascript進階程式設計》一書。
javascript 是物件導向的語言,自然也有物件導向的一些特性。
一:建構函式方式
第一步選擇類名,即建構函式的名字。下面的例子在建構函式裡不創造對象,而是使用this,使用new 運算子調用建構函式的時候在執行第一行代碼前先建立一個對象,這個對象只能用this訪問,然後可以直接賦予this屬性,預設情況下是建構函式的傳回值,不必return。
 例子:

function Car(sColor,iDoors)
{
    this.color = sColor;
    this.doors = iDoors;
    this.showColor = function()
    {
        alert(this.color);
    };
}
var oCar1 = new Car("red",4);//output red
var oCar2 = new Car("blue",3);//output blue

上面的例子會為每個對象都建立獨立的函數版本。再看下面的原型方式
二:原型方式:
該方式利用對象的prototype屬性,可把它看成建立新對象所依賴的原型。下面的例子使用空建構函式設定類名,然後所有的屬性和方法都直接賦予prototype屬性。在調用new Car()的時候原型的所有屬性都被立即賦予要建立的對象。
例子:function Car()
{
}
Car.prototype.color = "red";
Car.prototype.doors = 4;
Car.prototype.showColor = function()
{
     alert(this.color);
};
var oCar1 = new Car();//output red

上面的例子在建立多個執行個體後,對象的屬性值並沒有變。再看下面的混合的建構函式/原型方式
三:混合的建構函式/原型方式:
聯合使用建構函式和原型方式,就可以像其他程式設計語言楊建立對象。使用建構函式定義對象的所有非函數屬性,用原型方式定義對象的函數屬性。function Car(sColor,iDoors)
{
    this.color = sColor;
    this.doors = iDoors;
}
Car.prototype.showColor = function()
{
     alert(this.color);
};

var oCar1 = new Car("red",4);
var oCar2 = new Car("blue",3);

oCar1.showColor();//output red
oCar2.showColor();//output blue

四:動態原型方法:
動態原型方法的基本想法和混合的建構函式/原型方式相同,唯一的區別是賦予對象方法的位置,看下面的例子:function Car(sColor,iDoors)
{
    this.color = sColor;
    this.doors = iDoors;
    if(typeof Car.initialized == "undefined")//***
    {
        Car.prototype.showColor = function()
        {
             alert(this.color);
        };
        Car.initialized = true;//***
    }
}

上面的方法使用標誌initialized來判斷是否已給原型賦予任何方法,該方法只建立並賦值一次。

五:混合工廠方式
這種方式的目的是建立假建構函式,只返回一種對象的新執行個體:function Car()
{
    var tempCar = new Object;
    tempCar.color = "red";
    tempCar.doors = 4;
    tempCar.showColor = function()
    {
       alert(this.color);
    };
    return tempCar;
}
var oCar1 = new Car();

由於在Car()建構函式內部調用了new運算子,所以將忽略建構函式外的第2個new 運算子。不建議使用這種方式。

可以使用prototype屬性為任何已有的類定義新的方法。

相關文章

聯繫我們

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