亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript 常見對象類創(chuàng)建代碼與優(yōu)缺點分析

 更新時間:2009年12月07日 19:36:47   作者:  
這幾種javascript類定義方式中,最常用的是雜合prototype/constructor 和 動態(tài)prototype方式。
在Javascript中構建一個類有好幾種方法:
1.Factory 方式
復制代碼 代碼如下:

function createCar(){
var car = new Object();
car.color=”b”;
car.length=1;
car.run=function(){alert(”run”);}
return car;
}

定義這么一個函數(shù)之后,就可以用:
var car1 = createCar();
var car2 = createCar();
來創(chuàng)建新的對象,這種方式的問題是每一次創(chuàng)建一個car對象,run Function也都必須重新創(chuàng)建一次.浪費內存

2.Constructor方式
復制代碼 代碼如下:

function Car(){
this.color=”b”;
this.length=1;
this.run=function(){alert(”run”);}
}
var car1=new Car();
var car2=new Car();

這是最基本的方式,但是也存在和factory方式一樣的毛病

3.prototype方式
復制代碼 代碼如下:

function Car(){
}
Car.prototype.color=”b”;
Car.prototype.length=1;
Car.prototype.run=function(){alert(”run”);
}

這個方式的缺點是,當這個類有一個引用屬性時,改變一個對象的這個屬性也會改變其他對象得屬性
比如:
復制代碼 代碼如下:

Car.prototype.data1=new Array();
var car1=new Car();
var car2=new Car();
car1.data1.push(”a”);

此時,car2.data也就包含了”a”元素

4.Prototype/Constructor雜合方式 [常用]
復制代碼 代碼如下:

function Car(){
this.color=”b”;
this.length=1;
this.data1=new Array();
}
Car.prototype.run=function(){
alert(”dddd”);
}


這種方式去除了那些缺點.是目前比較大范圍使用的方式

5.動態(tài)prototype方式 [常用]
復制代碼 代碼如下:

function Car(){
this.color=”b”;
this.length=1;
this.data1=new Array();

if(typeof Car.initilize==”undefined”){
Car.prototype.run=function(){alert(”a”);}
}

Car.initilize=true;
}

這幾種方式中,最常用的是雜合prototype/constructor 和 動態(tài)prototype方式

相關文章

最新評論