javascript的class建立是個有意思的話題, 確切的說, OO的javascript就是比較有趣的, 因爲javascript並沒有在設計的時候定位爲OO. 下面的文章是轉的別人的, 集中於話題"javascript語言中的Class 的創建"
在Javascript中構建一個類有好幾種方法:
1.Factory 方式
var car = new Object();
car.color="b";
car.length=1;
car.run=function(){alert("run");}
return car;
}
定義這麼一個函數之後,就可以用:
var car1 = createCar();
var car2 = createCar();
重新創建一次.浪費內存
2.Constructor方式
this.color="b";
this.length=1;
this.run=function(){alert("run");}
}
var car1=new Car();
var car2=new Car();
3.prototype方式
}
Car.prototype.color="b";
Car.prototype.length=1;
Car.prototype.run=function(){alert("run");}
比如:
var car1=new Car();
var car2=new Car();
car1.data1.push("a");
4.Prototype/Constructor雜合方式
this.color="b";
this.length=1;
this.data1=new Array();
}
Car.prototype.run=function(){
alert("dddd");
}
5.動態prototype方式
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 和 動態prototype方式
本文轉自:http://www.80x86.cn/article.asp?id=1552