javaScript 的核心 ECMAScript 描述了該語(yǔ)言的語(yǔ)法和基本對(duì)象;
DOM 描述了處理網(wǎng)頁(yè)內(nèi)容的方法和接口;
BOM 描述了與瀏覽器進(jìn)行交互的方法和接口。
,一個(gè)完整的 Javascript 實(shí)現(xiàn)是由以下 3 個(gè)不同部分組成的:
核心(ECMAScript)文檔對(duì)象模型(DOM)瀏覽器對(duì)象模型(BOM)工廠方法:============<script type="text/javascript">function createCar() { var oTempCar = new Object; oTempCar.color = "blue"; oTempCar.doors = 4; oTempCar.mpg = 25; oTempCar.showColor = function() { document.write(this.color); }; return oTempCar;}var oCar1 = createCar();var oCar2 = createCar();oCar1.showColor();document.write("<br />")oCar2.showColor();</script>
2.=========構(gòu)造函數(shù)
<script type="text/javascript">function Car(sColor,iDoors,iMpg) { this.color = sColor; this.doors = iDoors; this.mpg = iMpg; this.showColor = function() { document.write(this.color); };}var oCar1 = new Car("red",4,23);var oCar2 = new Car("blue",3,25);oCar1.showColor();document.write("<br />")oCar2.showColor();</script></body>
3.構(gòu)造函數(shù)和工廠方法的區(qū)別:
首先在構(gòu)造函數(shù)內(nèi)沒(méi)有創(chuàng)建對(duì)象,而是使用 this 關(guān)鍵字。使用 new 運(yùn)算符構(gòu)造函數(shù)時(shí),在執(zhí)行第一行代碼前先創(chuàng)建一個(gè)對(duì)象,只有用 this 才能訪問(wèn)該對(duì)象。然后可以直接賦予 this 屬性,默認(rèn)情況下是構(gòu)造函數(shù)的返回值(不必明確使用 return 運(yùn)算符)。
現(xiàn)在,用 new 運(yùn)算符和類名 Car 創(chuàng)建對(duì)象,就更像 ECMAScript 中一般對(duì)象的創(chuàng)建方式了。
你也許會(huì)問(wèn),這種方式在管理函數(shù)方面是否存在于前一種方式相同的問(wèn)題呢?是的。
就像工廠函數(shù),構(gòu)造函數(shù)會(huì)重復(fù)生成函數(shù),為每個(gè)對(duì)象都創(chuàng)建獨(dú)立的函數(shù)版本。不過(guò),與工廠函數(shù)相似,也可以用外部函數(shù)重寫(xiě)構(gòu)造函數(shù),同樣地,這么做語(yǔ)義上無(wú)任何意義。這正是下面要講的原型方式的優(yōu)勢(shì)所在。
4.原型的方法創(chuàng)建對(duì)象:
<script type="text/javascript">function Car() {}Car.PRototype.color = "blue";Car.prototype.doors = 4;Car.prototype.mpg = 25;Car.prototype.showColor = function() { document.write(this.color);};var oCar1 = new Car();var oCar2 = new Car();oCar1.showColor();document.write("<br />")oCar2.showColor();</script>
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注