在Javascript中,一切都是對象,包括函數(shù)。在Javascript中并沒有真正的類,不能像C#,PHP等語言中用 class xxx來定義。但Javascript中提供了一種折中的方案:把對象定義描述為對象的配方(先看一下例子會比較容易理解)。
定義類的方法有很多種,這里有兩中較為通用的方法,大家參考一下。
這兩種方法均可以解決構(gòu)造函數(shù)會重復生成函數(shù),為每個對象都創(chuàng)建獨立版本的函數(shù)的問題。
解決了重復初始化函數(shù)和函數(shù)共享的問題。
1、混合的構(gòu)造函數(shù)/原型方式
<code>
//混合的構(gòu)造函數(shù)/原型方式
//創(chuàng)建對象
function Card(sID,ourName){
this.ID = sID;
this.OurName = ourName;
this.Balance = 0;
}
Card.prototype.SaveMoney = function(money){
this.Balance += money;
};
Card.prototype.ShowBalance = function(){
alert(this.Balance);
};
//使用對象
var cardAA = new Card(1000,'james');
var cardBB = new Card(1001,'sun');
cardAA.SaveMoney(30);
cardBB.SaveMoney(80);
cardAA.ShowBalance();
cardBB.ShowBalance();
</code>
2、動態(tài)原型方法
<code>
//動態(tài)原型方法
//創(chuàng)建對象
function Card(sID,ourName){
this.ID = sID;
this.OurName = ourName;
this.Balance = 0;
if(typeof Card._initialized == "undefined"){
Card.prototype.SaveMoney = function(money){
this.Balance += money;
};
Card.prototype.ShowBalance = function(){
alert(this.Balance);
};
Card._initialized = true;
}
}
//使用對象
var cardAA = new Card(1000,'james');
var cardBB = new Card(1001,'sun');
cardAA.SaveMoney(30);
cardBB.SaveMoney(80);
cardAA.ShowBalance();
cardBB.ShowBalance();
</code>