当它进入第21行时,它认为没有功能存款 我觉得它应该有这个功能。请解释原因。
1 function makeBankAccount(){
2 var bala = 0
3 function balance(b)
4 {
5 return bala;
6 }
7 function withdraw(b)
8 {
9 bala = bala - b;
10 }
11 function deposit(b)
12 {
13 bala = bala + b;
14 }
15 return makeBankAccount;
16 }
17
18 var account1 = makeBankAccount();
19 var account2 = makeBankAccount();
20
21 account1.deposit(5);
22 console.log(account1.balance()); // -> 5
23 account1.withdraw(5);
24 console.log(account1.balance()); // -> 0
25
26 account2.withdraw(5);
27 account2.withdraw(5);
28 account2.deposit(5);
29 account2.deposit(5);
30 account2.deposit(5);
31 account2.deposit(5);
32 console.log(account2.balance()); // -> 10
答案 0 :(得分:0)
这是因为您的函数deposit(b)
不是全局函数。
deposit(b)
只能在make makeBankAccount()
内访问,并且您的对象位于外部。所以deposit(b)
超出了范围。
对象创建中也缺少new
个关键字。
将其更改为:
对象1:
var account1 = new makeBankAccount();
对象2:
var account2 = new makeBankAccount();
答案 1 :(得分:0)
有两种方法可以做到这一点:
function makeBankAccount(){
var bala = 0
function balance(b) {
return bala;
}
function withdraw(b) {
bala = bala - b;
}
function deposit(b) {
bala = bala + b;
}
return {
balance: balance,
withdraw: withdraw,
deposit: deposit
};
}
然后您的使用代码将保持不变
或
function makeBankAccount(){
this.bala = 0
}
makeBankAccount.prototype.balance = function(b) {
return this.bala;
};
makeBankAccount.prototype.withdraw = function(b) {
this.bala -= b;
};
makeBankAccount.prototype.deposit = function (b) {
this.bala += b;
};
然后你的实例化帐户1 /帐户2就像
var account1 = new makeBankAccount();
var account2 = new makeBankAccount();
其余代码保持不变
答案 2 :(得分:0)
试试这个:
var balance = 10; //You may have the balance saved anywhere else. Get it here.
var makeBankAccount = {
amount: 0,
balance: function () {
return balance;
},
withdraw: function () {
return balance - this.amount;
},
deposit: function () {
return balance + this.amount;
}
}
function Balance() {
document.getElementById("Balance").innerHTML = makeBankAccount.balance();
}
function Withdraw(x) {
makeBankAccount.amount = x;
document.getElementById("Withdraw").innerHTML = makeBankAccount.withdraw();
}
function Deposit(x) {
makeBankAccount.amount = x;
document.getElementById("Deposit").innerHTML = makeBankAccount.deposit();
}
<html>
<body>
<button onclick="Balance()">Balance</button>
<button onclick="Withdraw(6)">Withdraw</button>
<button onclick="Deposit(7)">Deposit</button>
<p id="Balance"></p>
<p id="Withdraw"></p>
<p id="Deposit"></p>
</body>
</html>
剩下的就是获取balance
并将amount
传递给函数。