日新网培训Javascript之六 面向对象例子借书小程序
学习面向对象的借书小例子,理解实体类和面向对象思想。
代码
function BookData(BId, BName, BHasOut, BPrice) { ///实体对象
this.Id = BId;
this.Name = BName;
this.HasOut = BHasOut;
this.Price = BPrice;
};
Libary = [
[1,"C#程序设计",1,100],[2,"C标准库",1,200],[3,"网络编程",1,200]
];
Libary.FindBookById = function(id) {
for (var i = 0; i < this.length; i++) {
if (Libary[i][0] == id) {
if (Libary[i][2] == 0) {
alert("虽然有这本书,但已经被借走.");
return;
}
Libary[i][2] = 0;
alert("借书成功");
return new BookData(Libary[i][0], Libary[i][1], Libary[i][2], Libary[i][3]);
}
}
return "NotFind";
};
function Book(Id) {
this.Data = Libary.FindBookById(Id);
if (this.Data === "NotFind") {
alert("未找到图书");
}
};
Book.prototype.Return = function() {
for (var i = 0; i < Libary.length; i++) {
if (Libary[i][0] == this.Data.Id) {
Libary[i][2] = 1;
}
}
this.Data = undefined;
};
Book.prototype.PayBook = function() {
for (var i = 0; i < Libary.length; i++) {
if (Libary[i][0] == this.Data.Id) {
alert(Libary[i][3]);
}
}
};
Book.prototype.ReBorrow = function() {
//继续借
};
this.Id = BId;
this.Name = BName;
this.HasOut = BHasOut;
this.Price = BPrice;
};
Libary = [
[1,"C#程序设计",1,100],[2,"C标准库",1,200],[3,"网络编程",1,200]
];
Libary.FindBookById = function(id) {
for (var i = 0; i < this.length; i++) {
if (Libary[i][0] == id) {
if (Libary[i][2] == 0) {
alert("虽然有这本书,但已经被借走.");
return;
}
Libary[i][2] = 0;
alert("借书成功");
return new BookData(Libary[i][0], Libary[i][1], Libary[i][2], Libary[i][3]);
}
}
return "NotFind";
};
function Book(Id) {
this.Data = Libary.FindBookById(Id);
if (this.Data === "NotFind") {
alert("未找到图书");
}
};
Book.prototype.Return = function() {
for (var i = 0; i < Libary.length; i++) {
if (Libary[i][0] == this.Data.Id) {
Libary[i][2] = 1;
}
}
this.Data = undefined;
};
Book.prototype.PayBook = function() {
for (var i = 0; i < Libary.length; i++) {
if (Libary[i][0] == this.Data.Id) {
alert(Libary[i][3]);
}
}
};
Book.prototype.ReBorrow = function() {
//继续借
};
测试代码:
代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script src="JScript.js" type="text/javascript"></script>
<script>
var b = new Book(2);
b.Return();
var bb = new Book(2);
</script>
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script src="JScript.js" type="text/javascript"></script>
<script>
var b = new Book(2);
b.Return();
var bb = new Book(2);
</script>
</body>
</html>