javaScript 的核心 ECMAScript 描述了該語言的語法和基本對象;
DOM 描述了處理網(wǎng)頁內(nèi)容的方法和接口;
BOM 描述了與瀏覽器進(jìn)行交互的方法和接口。
,一個完整的 Javascript 實現(xiàn)是由以下 3 個不同部分組成的:
核心(ECMAScript)文檔對象模型(DOM)瀏覽器對象模型(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)沒有創(chuàng)建對象,而是使用 this 關(guān)鍵字。使用 new 運算符構(gòu)造函數(shù)時,在執(zhí)行第一行代碼前先創(chuàng)建一個對象,只有用 this 才能訪問該對象。然后可以直接賦予 this 屬性,默認(rèn)情況下是構(gòu)造函數(shù)的返回值(不必明確使用 return 運算符)。
現(xiàn)在,用 new 運算符和類名 Car 創(chuàng)建對象,就更像 ECMAScript 中一般對象的創(chuàng)建方式了。
你也許會問,這種方式在管理函數(shù)方面是否存在于前一種方式相同的問題呢?是的。
就像工廠函數(shù),構(gòu)造函數(shù)會重復(fù)生成函數(shù),為每個對象都創(chuàng)建獨立的函數(shù)版本。不過,與工廠函數(shù)相似,也可以用外部函數(shù)重寫構(gòu)造函數(shù),同樣地,這么做語義上無任何意義。這正是下面要講的原型方式的優(yōu)勢所在。
4.原型的方法創(chuàng)建對象:
<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>
新聞熱點
疑難解答