在Javascript中,一切都是对象,包括函数。在Javascript中并没有真正的类,不能像C#,PHP等语言中用 class xxx来定义。但Javascript中提供了一种折中的方案:把对象定义描述为对象的配方(先看一下例子会比较容易理解)。
定义类的方法有很多种,这里有两中较为通用的方法,大家参考一下。
这两种方法均可以解决 构造函数会重复生成函数,为每个对象都创建独立版本的函数的问题。
解决了重复初始化函数和函数共享的问题。
1、混合的构造函数/原型方式
01.
//混合的构造函数/原型方式
02.
//创建对象
03.
function
Card(sID,ourName){
04.
this
.ID = sID;
05.
this
.OurName = ourName;
06.
this
.Balance = 0;
07.
}
08.
09.
Card.prototype.SaveMoney =
function
(money){
10.
this
.Balance += money;
11.
};
12.
13.
Card.prototype.ShowBalance =
function
(){
14.
alert(
this
.Balance);
15.
};
16.
17.
//使用对象
18.
var
cardAA =
new
Card(1000,
'james'
);
19.
var
cardBB =
new
Card(1001,
'sun'
);
20.
21.
cardAA.SaveMoney(30);
22.
cardBB.SaveMoney(80);
23.
24.
cardAA.ShowBalance();
25.
cardBB.ShowBalance();
01.
//动态原型方法
02.
//创建对象
03.
function
Card(sID,ourName){
04.
this
.ID = sID;
05.
this
.OurName = ourName;
06.
this
.Balance = 0;
07.
if
(
typeof
Card._initialized ==
"undefined"
){
08.
Card.prototype.SaveMoney =
function
(money){
09.
this
.Balance += money;
10.
};
11.
12.
Card.prototype.ShowBalance =
function
(){
13.
alert(
this
.Balance);
14.
};
15.
Card._initialized =
true
;
16.
}
17.
}
18.
19.
//使用对象
20.
var
cardAA =
new
Card(1000,
'james'
);
21.
var
cardBB =
new
Card(1001,
'sun'
);
22.
23.
24.
cardAA.SaveMoney(30);
25.
cardBB.SaveMoney(80);
26.
27.
cardAA.ShowBalance();
28.
cardBB.ShowBalance();
出处: