建立|對象
要建立自己的對象執行個體,必須首先為其定義一個建構函式。建構函式建立一個新對象,賦予對象屬性,並在合適的時候賦予方法。例如,下面的樣本為 pasta 對象定義了建構函式。注意 this 關鍵字的使用,它指向當前對象。
// pasta 是有四個參數的構造器。function pasta(grain, width, shape, hasEgg){ // 是用什麼糧食做的? this.grain = grain; // 多寬?(數值) this.width = width; // 橫截面形狀?(字串) this.shape = shape; // 是否加蛋黃?(boolean) this.hasEgg = hasEgg; }
定義了物件建構器後,用 new 運算子建立對象執行個體。
var spaghetti = new pasta("wheat", 0.2, "circle", true);var linguine = new pasta("wheat", 0.3, "oval", true);
可以給對象執行個體添加屬性以改變該執行個體,但是用相同的構造器產生的其他對象定義中並不包括這些屬性,而且除非你特意添加這些屬性那麼在其他執行個體中並不顯示出來。如果要將對象所有執行個體的附加屬性顯示出來,必須將它們添加到建構函式或構造器原型對象(原型在進階文檔中討論)中。
// spaghetti 的附加屬性。spaghetti.color = "pale straw";spaghetti.drycook = 7;spaghetti.freshcook = 0.5;var chowFun = new pasta("rice", 3, "flat", false); // chowFun 對象或其他現有的 pasta 對象// 都沒有添加到 spaghetti 對象// 的三個新屬性。// 將屬性‘foodgroup’加到 pasta 原型對象// 中,這樣 pasta 對象的所有執行個體都可以有該屬性,// 包括那些已經產生的執行個體。pasta.prototype.foodgroup = "carbohydrates"// 現在 spaghetti.foodgroup、chowFun.foodgroup,等等// 均包含值“carbohydrates”。
在定義中包含方法
可以在對象的定義中包含方法(函數)。一種方法是在引用別處定義的函數的建構函式中添加一個屬性。例如,下面的樣本擴充上面定義的 pasta 建構函式以包含 toString 方法,該方法將在顯示對象的值時被調用。
// pasta 是有四個參數的構造器。// 第一部分與上面相同。function pasta(grain, width, shape, hasEgg){ // 用什麼糧食做的? this.grain = grain; // 多寬?(數值) this.width = width; // 橫截面形狀?(字串) this.shape = shape; // 是否加蛋黃?(boolean) this.hasEgg = hasEgg; // 這裡添加 toString 方法(如下定義)。 // 注意在函數的名稱後沒有加圓括弧; // 這不是一個函數調用,而是 // 對函數自身的引用。 this.toString = pastaToString;}// 實際的用來顯示 past 對象內容的函數。function pastaToString(){ // 返回對象的屬性。 return "Grain: " + this.grain + "\n" + "Width: " + this.width + "\n" + "Shape: " + this.shape + "\n" + "Egg?: " + Boolean(this.hasEgg);}var spaghetti = new pasta("wheat", 0.2, "circle", true);// 將調用 toString() 並顯示 spaghetti 對象// 的屬性(需要Internet 瀏覽器)。window.alert(spaghetti);