我有一个名为 bank
的对象,当用户存入例如 50
欧元时,余额始终为 0
。老实说,我不明白为什么?我的方法 deposit()
不正确?
var bank = {
name : "Depuis",
firstname : "Denis",
accountNumber : "BE42-1525899822",
email : "depuis.denisf@gmail.com",
phone : "010.49.48.00",
balance : 0.0
};
deposit(50);
console.log("Balance is of => " + bank.balance);
function deposit(amount){
if(amount > 0){
this.balance += amount;
console.log("The amount is of " + amount + " euros.");
}
}
答案 0 :(得分:2)
您应该考虑如何使用 this 运算符。在此网站中,您可以搜索更多信息:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
查看下一个示例:
const test = {
prop: 42,
func: function() {
return this.prop;
},
};
console.log(test.func());
// expected output: 42
在此代码示例中使用了 function 关键字,因此 this 关键字可用于访问对象字段。你应该考虑到它内部调用的每个函数都可以使用 this 操作符来获取相同的对象引用。
答案 1 :(得分:1)
this
内部的存款函数不是指bank
对象,而是指window
对象,这是因为该函数的调用方式。
您可以在银行对象中添加一个方法,该方法可以调用 deposit
函数,该函数将使 this
引用银行对象。
this
是根据上下文设置的。在下面的代码段中,deposit
函数以类似的方式被调用,但来自不同的上下文,它以不同的方式设置 this
。
您应该阅读评论中提到的有关 this
如何工作的更多信息。
var bank = {
name : "Depuis",
firstname : "Denis",
accountNumber : "BE42-1525899822",
email : "depuis.denisf@gmail.com",
phone : "010.49.48.00",
balance : 0.0,
depositAmt: function(amount) {
deposit(amount)
}
};
bank.depositAmt(50);
console.log("Balance is of => " + bank.balance);
function deposit(amount){
if(amount > 0){
// this now refers to the bank object
this.balance += amount;
console.log("The amount is of " + amount + " euros.");
}
}
或者你可以直接引用 bank
对象。
var bank = {
name : "Depuis",
firstname : "Denis",
accountNumber : "BE42-1525899822",
email : "depuis.denisf@gmail.com",
phone : "010.49.48.00",
balance : 0.0
};
deposit(50);
console.log("Balance is of => " + bank.balance);
function deposit(amount){
if(amount > 0){
// this here does not refer to that
// it refers to the window
bank.balance += amount;
console.log("The amount is of " + amount + " euros.");
}
}
答案 2 :(得分:1)
您需要调用该函数并将上下文设置为 bank
。
const bank = {
name: "Depuis",
firstname: "Denis",
accountNumber: "BE42-1525899822",
email: "depuis.denisf@gmail.com",
phone: "010.49.48.00",
balance: 0.0
};
deposit.call(bank, 50); // Call with context of the bank.
console.log(`Current balance: ${bank.balance} euros`);
function deposit(amount) {
if (amount > 0) {
this.balance += amount;
console.log(`The amount is of ${amount} euros.`);
}
}
更好的替代方法是使用 OOP 并创建一个可以访问和修改帐户余额的 Bank
对象。
const main = () => {
const bank = new Bank({ currencyType: '€' });
const customer = bank.createCustomer({
givenName: "Denis",
surname: "Depuis",
email: "depuis.denisf@gmail.com",
phone: "010.49.48.00"
});
const { accountNumber } = customer;
console.log(customer.greeting());
bank.deposit(accountNumber, 50.25);
bank.withdraw(accountNumber, 20.10);
};
const defaultCustomerProperties = {
givenName: '',
surname: '',
email: '',
phone: '',
balance: 0.00
};
class Customer {
constructor(options) {
const opts = { ...defaultCustomerProperties, ...options };
this.accountNumber = opts.accountNumber;
this.givenName = opts.givenName;
this.surname = opts.surname;
this.email = opts.email;
this.phone = opts.phone;
this.balance = opts.balance;
}
greeting() {
return `Welcome ${this.givenName}! (${this.accountNumber})`;
}
}
class Bank {
constructor(options = {}) {
this.currencyType = options.currencyType || '$';
this.customers = {};
}
createCustomer(options) {
const accountNumber = `BExx-xxxxxxxxxx`.replace(/x/g, g => Math.floor(Math.random() * 10));
const account = new Customer({ ...options, accountNumber });
this.customers[accountNumber] = account;
return account;
}
findCustomer(accountId) {
const customer = this.customers[accountId];
if (customer == null) {
throw new Error(`Account by [id=${accountId}] not found!`);
}
return customer;
}
deposit(accountId, amount) {
const customer = this.findCustomer(accountId);
customer.balance += amount;
console.log(`Deposited ${this.formatCurrency(amount)} into ${accountId}. New balance: ${this.formatCurrency(customer.balance)}`);
}
withdraw(accountId, amount) {
const customer = this.findCustomer(accountId);
if (customer.balance < amount) {
throw new Error(`Customer balance is less than the desired amount!`);
}
customer.balance -= amount;
console.log(`Withdrew ${this.formatCurrency(amount)} from ${accountId}. New balance: ${this.formatCurrency(customer.balance)}`);
}
formatCurrency(amount) {
return `${this.currencyType}${amount.toFixed(2)}`;
}
retrieveBalance(accountId) {
const customer = this.findCustomer(accountId);
return customer.balance;
}
};
main();
.as-console-wrapper { top: 0; max-height: 100% !important; }