Why does my last customer entry override the previous entry instead of adding it to the customer object? JS Any help would be much appreciated.
class Bank {
constructor() {
this.customers = {};
}
}
Bank.prototype.addCustomer = function (customer) {
this.customers = customer;
return this;
}
var bank = new Bank();
var newCustomer1 = bank.addCustomer('Curtis');
var newCustomer2 = bank.addCustomer('Alice');
console.log(bank.customers);
First, customers is not an array, you have declared it as a Javascript Object.
Second, when you change it to an array, use the push method to add elements to the end of the array.
I've changed your code accordingly.
class Bank {
constructor() {
// Change 2
this.customers = [];
}
}
// Change 2
Bank.prototype.addCustomer = function (customer) {
this.customers.push(customer);
}
var bank = new Bank();
bank.addCustomer('Curtis');
bank.addCustomer('Alice');
console.log(bank.customers);