JavaScript 中的原型继承



我是javascript的原型继承和js面向对象编程的新手。我试图创建一个基本对象,帐户,然后从中继承检查帐户。以下是我的代码。

function Account(fName, lName) {
this.firstName = fName;
this.lastName = lName;
}
Account.prototype.balance = function() {
console.log("This is the balance");
}
function CheckingAccount() {
this.salary = 10000;
}
CheckingAccount.prototype = Object.create(Account.prototype);
let account = new Account("John", "Doe");
let checking = new CheckingAccount();
CheckingAccount.balance();

当我在Visual Studio上运行它时,我收到以下错误:"未捕获的类型错误:CheckingAccount.balance不是一个函数">

你想在实例上调用方法而不是 Class 对象(例如,checking不是CheckingAccount(。 此外,请确保更改构造函数。如需进一步阅读,请参阅 MDN 文档。

您可以在此处看到这些更改:

function Account(fName, lName) {
this.firstName = fName;
this.lastName = lName;
this.salary = 0;
}
Account.prototype.balance = function() {
return this.salary;    // you'll probably not use _only_ salary here
}
function CheckingAccount() {
this.salary = 10000;
}
CheckingAccount.prototype = Object.create(Account.prototype);
// Make sure to update the constructor
Object.defineProperty(CheckingAccount.prototype, 'constructor', {
value: CheckingAccount,
enumerable: false, // so that it does not appear in 'for in' loop
writable: true
});
let account  = new Account("John", "Doe");
let checking = new CheckingAccount();
console.log('account balance:',      account.balance())
console.log('checking balance:',     checking.balance())
console.log('account constructor:',  account.constructor);
console.log('checking constructor:', checking.constructor);

您可以在 ES6 中使用正确的class关键字来执行此操作。 下面是一个扩展它的帐户和支票示例。 这里Account类有一个balancedepositshowBook函数,只有子类Chequing有一个writeCheque函数。然而,Chequing实例仍然可以调用所有父类函数,因为它是一个Account

class Account {
constructor(name) {
this.name = name;
this.amount = 0;
}
balance() {
return this.amount
}
deposit(sum) {
this.amount += sum;
}
showBook() {
console.log("-------------------------");
console.log("Account for",this.name);
console.log(`Balance: $${this.amount}`);
}
}
class Chequing extends Account {
constructor(name) {
super(name);
this.cheques = [];
}
writeCheque(sum, to) {
this.amount -= sum;
this.cheques.push({number: this.cheques.length+1, recipient: to, amount: sum});
}
showBook() {
super.showBook();
if (this.cheques.length > 0) {
console.log("Cheque activity:");
for (const cheque of this.cheques) {
console.log(`  ${cheque.number}: $${cheque.amount} paid to ${cheque.recipient}`);
}
}
else console.log("No cheques have been written");
}
}
const ch1 = new Chequing("Mary Jones");
ch1.deposit(1000);
ch1.showBook();
ch1.writeCheque(95, "Bob Smith");
ch1.writeCheque(485, "Ritz Hotel");
ch1.showBook();

帐户在这里是类。支票账户也是类。帐户检查是实例。

如果您希望CheckingAccount继承自Account类,您应该这样做:

CheckingAccount.prototype = Object.create(Account.prototype);

这会将检查帐户的原型对象委托给帐户原型对象。

CheckingAccount函数中没有余额属性(函数是javascript中的一类对象(,它上面只有原型属性。虽然余额属性(同时是函数(驻留在对象上,但 Account 的原型属性指向该对象(余额函数简而言之位于 Account.prototype 对象内部(。

可从以下位置访问balance()函数:

  • 帐户原型
  • CheckingAccount.prototype(因为 Object.create 函数你 使用(
  • 从这两个类的任何实例。

最新更新