要創建自己的對象實例,必須首先為其定義一個構造函數。構造函數創建一個新對象,賦予對象屬性,并在合適的時候賦予方法。例如,下面的示例為 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);
新聞熱點
疑難解答