'How to access a property inside an object and use in another method? javascript
I need to create a method to return a customers name and bank account value like so:
*bank.printAccount('Sheldon'); // this should print 'Sheldon account is 0'*
However I am struggling to find out how to access the property customers to use in a method printAccount. Currently I have this:
class Bank {
constructor(){
this.customers = {};
}
}
Bank.prototype.addCustomer = function(customer){
this.customers[customer] = 0;
}
Bank.prototype.printAccount = function(){
};
var bank = new Bank();
bank.addCustomer('Sheldon');
bank.addCustomer('Bob');
Solution 1:[1]
There you go:
class Bank {
constructor() {
this.customers = {};
}
}
Bank.prototype.addCustomer = function(customer) {
this.customers[customer] = 0;
}
Bank.prototype.printAccount = function(customer) {
console.log(this.customers[customer])
};
var bank = new Bank();
bank.addCustomer('Sheldon');
bank.addCustomer('Bob');
bank.printAccount('Sheldon');
bank.printAccount('Bob');
You probably will need to add edge cases in printAccount()
such as to check whether the customer exists or not.
Edit: Removed doubled initialization of customers
.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |