?
Dieses Dokument verwendet PHP-Handbuch für chinesische Websites Freigeben
JScript? | 語言參考 |
要?jiǎng)?chuàng)建自己的對象實(shí)例,必須首先為其定義一個(gè)構(gòu)造函數(shù)。構(gòu)造函數(shù)創(chuàng)建一個(gè)新對象,賦予對象屬性,并在合適的時(shí)候賦予方法。例如,下面的示例為 pasta 對象定義了構(gòu)造函數(shù)。注意 this 關(guān)鍵字的使用,它指向當(dāng)前對象。
// pasta
是有四個(gè)參數(shù)的構(gòu)造器。function pasta(grain, width, shape, hasEgg)
{//
是用什么糧食做的?this.grain = grain;
//
多寬?(數(shù)值)this.width = width;
//
橫截面形狀?(字符串)this.shape = shape;
//
是否加蛋黃?(boolean
)this.hasEgg = hasEgg;
}
定義了對象構(gòu)造器后,用 new 運(yùn)算符創(chuàng)建對象實(shí)例。
var spaghetti = new pasta("wheat", 0.2, "circle", true);
var linguine = new pasta("wheat", 0.3, "oval", true);
可以給對象實(shí)例添加屬性以改變該實(shí)例,但是用相同的構(gòu)造器生成的其他對象定義中并不包括這些屬性,而且除非你特意添加這些屬性那么在其他實(shí)例中并不顯示出來。如果要將對象所有實(shí)例的附加屬性顯示出來,必須將它們添加到構(gòu)造函數(shù)或構(gòu)造器原型對象(原型在高級文檔中討論)中。
// spaghetti
的附加屬性。spaghetti.color = "pale straw";
spaghetti.drycook = 7;
spaghetti.freshcook = 0.5;
var chowFun = new pasta("rice", 3, "flat", false);
// chowFun
對象或其他現(xiàn)有的pasta
對象//
都沒有添加到spaghetti
對象//
的三個(gè)新屬性。//
將屬性‘foodgroup
’加到pasta
原型對象//
中,這樣pasta
對象的所有實(shí)例都可以有該屬性,//
包括那些已經(jīng)生成的實(shí)例。pasta.prototype.foodgroup = "carbohydrates"
//
現(xiàn)在spaghetti.foodgroup
、chowFun.foodgroup
,等等//
均包含值“carbohydrates
”。
可以在對象的定義中包含方法(函數(shù))。一種方法是在引用別處定義的函數(shù)的構(gòu)造函數(shù)中添加一個(gè)屬性。例如,下面的示例擴(kuò)充上面定義的 pasta 構(gòu)造函數(shù)以包含 toString 方法,該方法將在顯示對象的值時(shí)被調(diào)用。
// pasta
是有四個(gè)參數(shù)的構(gòu)造器。//
第一部分與上面相同。function pasta(grain, width, shape, hasEgg)
{//
用什么糧食做的?this.grain = grain;
//
多寬?(數(shù)值)this.width = width;
//
橫截面形狀?(字符串)this.shape = shape;
//
是否加蛋黃?(boolean
)this.hasEgg = hasEgg;
//
這里添加toString
方法(如下定義)。//
注意在函數(shù)的名稱后沒有加圓括號;//
這不是一個(gè)函數(shù)調(diào)用,而是//
對函數(shù)自身的引用。this.toString = pastaToString;
}//
實(shí)際的用來顯示past
對象內(nèi)容的函數(shù)。
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);
//
將調(diào)用toString()
并顯示spaghetti
對象//
的屬性(需要Internet
瀏覽器)。window.alert(spaghetti);