用JavaScript实现继承

3

我有一个JavaScript中的账户类(Account Class),这是我的父类。DepositAccount和SavingsAccount是子类。所有这些类都在外部JavaScript文件中。这些类包括:

function account(accountNum, type)
{
    this.accountNum = accountNum;
    this.type = type;
}

function depositAccount(accountNum,type, balance, credit)
{


    this.balance = balance;
    this.credit = credit;   
    account.call(this, accountNum,type);
};


function savingAccount(accountNum,type, amount, yearlyPrime)
{

    this.amount = amount;
    this.yearlyPrime = yearlyPrime;
    account.call(this, accountNum, type);
};

在我的html页面中,我有另一个脚本,我正在尝试初始化储蓄账户,也就是说,我想创建一个账户子实例——储蓄账户。在deposit account类的call方法中,我得到了一个未捕获的错误。
我能得到帮助吗?我做错了什么吗? html脚本:
<script> 
var account = new account(232, "young");
var deposit = new depositaccount(232, "young", 1000, 2555);
</script>

1
不确定您是否在这里打错了字,但第二个 new account() 应该是 new depositAccount() 吗?使用您提供的代码,否则将传递太多参数。 - James Donnelly
这是一个打字错误。仍然无法运行。 - user2674835
2个回答

4
var account = new account(232, "young");

你正在用account函数的对象替换account函数。
建议:
这是JavaScript程序员遵循的一种约定,使用函数名的首字母大写。

我不敢相信它是如此简单!谢谢! - user2674835
I will, in 3 minutes :) - user2674835

0
你可能想在这里使用Mixin模式,它是一个非常有用的设计模式,适用于像你这样的问题。
编辑:忘记Mixin吧,虽然它可以工作,但是有一种不同的方式,以下是更接近你的问题的子类化方法。
例如:
var Account = function(accountNum, type) {
    this.accountNum = accountNum;
    this.type = type;
}

var DepositAccount = function(accountNum, balance, credit) {
    Account.call(this, accountNum, 'deposit');
    this.balance = balance;
    this.credit = credit;   
};

DepositAccount.prototype = Object.create(Account.prototype);
var myAccount = new DepositAccount('12345', '100.00', '10');

我不明白你在建议什么。 - user2674835

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接