欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javascript 類(lèi)定義的4種方法

 更新時(shí)間:2009年09月12日 21:51:47   作者:  
javascript 類(lèi)定義的4種方法,大家可以參考下根據(jù)需要選擇。
復(fù)制代碼 代碼如下:

/*
工廠方式--- 創(chuàng)建并返回特定類(lèi)型的對(duì)象的 工廠函數(shù) ( factory function )
*/
function createCar(color,doors,mpg){
var tempCar = new Object;
tempCar.color = color;
tempCar.doors = doors;
tempCar.mpg = mpg;
tempCar.showCar = function(){
alert(this.color + " " + this.doors);
}
return tempCar;
}

/*
構(gòu)造函數(shù)方式--- 構(gòu)造函數(shù)看起來(lái)很像工廠函數(shù)
*/
function Car(color,doors,mpg){
this.color = color;
this.doors = doors;
this.mpg = mpg;
this.showCar = function(){
alert(this.color);
};
}
/*
原型方式--- 利用了對(duì)象的 prototype 屬性,可把它看成創(chuàng)建新對(duì)象所依賴(lài)的原型
*/
function Car(color,doors,mpg){
this.color = color;
this.doors = doors;
this.mpg = mpg;
this.drivers = new Array("nomad","angel");
}

Car.prototype.showCar3 = function(){
alert(this.color);
};

/*
混合的構(gòu)造函數(shù) /原型方式--- 用構(gòu)造函數(shù)定義對(duì)象的所有非函數(shù)屬性,用原型方式定義對(duì)象的函數(shù)屬性(方法)
*/
function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike", "Sue");
}

Car.prototype.showColor = function () {
alert(this.color);
};
/*
動(dòng)態(tài)原型方法--- 在構(gòu)造函數(shù)內(nèi)定義非函數(shù)屬性,而函數(shù)屬性則利用原型屬性定義。唯一的區(qū)別是賦予對(duì)象方法的位置。
*/
function Car(sColor, iDoors, iMpg) {
this.color = sColor;
this.doors = iDoors;
this.mpg = iMpg;
this.drivers = new Array("Mike", "Sue");

if (typeof Car._initialized == "undefined") {

Car.prototype.showColor = function () {
alert(this.color);
};

Car._initialized = true;
}
} //該方法使用標(biāo)志( _initialized )來(lái)判斷是否已給原型賦予了任何方法。

相關(guān)文章

  • js繼承 Base類(lèi)的源碼解析

    js繼承 Base類(lèi)的源碼解析

    Base據(jù)說(shuō)是最好的js繼承的封裝類(lèi),最近讀了一下base2.js的繼承部分,現(xiàn)在將源碼的解析貼下,有錯(cuò)誤的地方希望大家指出,我會(huì)更新的.
    2008-12-12
  • 關(guān)于JavaScript定義類(lèi)和對(duì)象的幾種方式

    關(guān)于JavaScript定義類(lèi)和對(duì)象的幾種方式

    在說(shuō)這個(gè)話題之前,我想先說(shuō)幾句題外話:最近偶然碰到有朋友問(wèn)我“hoisting”的問(wèn)題。即在js里所有變量的聲明都是置頂?shù)模x值則是在之后發(fā)生的。
    2010-11-11
  • JavaScript類(lèi)和繼承 this屬性使用說(shuō)明

    JavaScript類(lèi)和繼承 this屬性使用說(shuō)明

    本文介紹了JavaScript里面的this屬性。這個(gè)屬性是理解JavaScript類(lèi)和繼承的重要基礎(chǔ)。
    2010-09-09
  • javascript面向?qū)ο笾?命名空間

    javascript面向?qū)ο笾?命名空間

    javascript中本沒(méi)有命名空間的概念,但是要體現(xiàn)面向?qū)ο蟮乃枷?,?yīng)當(dāng)有命名空間,就像java中的package,.net中的namespace一樣,作用主要為了防止類(lèi)名沖突,相同的類(lèi)名只要屬于不同的命名空間,便不會(huì)沖突。
    2011-02-02
  • javascript 面向?qū)ο笕吕砭氈^承與多態(tài)

    javascript 面向?qū)ο笕吕砭氈^承與多態(tài)

    前面我們討論了如何在 JavaScript 語(yǔ)言中實(shí)現(xiàn)對(duì)私有實(shí)例成員、公有實(shí)例成員、私有靜態(tài)成員、公有靜態(tài)成員和靜態(tài)類(lèi)的封裝。這次我們來(lái)討論一下面向?qū)ο蟪绦蛟O(shè)計(jì)中的另外兩個(gè)要素:繼承與多態(tài)。
    2009-12-12
  • js面向?qū)ο?多種創(chuàng)建對(duì)象方法小結(jié)

    js面向?qū)ο?多種創(chuàng)建對(duì)象方法小結(jié)

    js面向?qū)ο?多種創(chuàng)建對(duì)象方法小結(jié),需要的朋友可以參考下
    2012-05-05
  • 最新評(píng)論