rt.
用function 分別定義Person和Account類模型,其中Account從Person繼承,並重寫toString()方法
<script type="text/javascript">
function go() {
var acc1 = new Account('Taro', 'Shibuya1-1-2', '1001', 20000);
var acc2 = new Account('Hanako', 'Akasaka2-3-4', '1002', 35000);
acc1.toString();
acc2.toString();
}
// 定義Person構造器
function Person(name, address) {
this.name = name;
this.address = address;
}
// 在Person.property中添加toString方法
Person.prototype.toString = function() {
document.write(this.name + " " + this.address + "<br>");
}
// 定義Account構造器
function Account(name, address, number, amount) {
// 從Person繼承
this.newObj = Person;
this.newObj(name, address);
delete this.newObj;
// Account特有屬性
this.number = number;
this.amount = amount;
}
Account.prototype = Object.create(Person.prototype);
// 設置"constructor" 屬性指向Account
Account.prototype.constructor = Account;
// 更改Person中toString方法
Account.prototype.toString = function() {
document.write(this.name + " " + this.address
+ " " + this.amount + "<br>");
}
Account.prototype.deposit = function(x) {
this.amount += x;
}
Account.prototype.withdraw = function(x) {
this.amount -= x;
}
</script>