0

I have an object named bank, when the user deposits for example 50 euros, tha balance is always of 0. Sincerely, I don't see why? My method deposit() isn't correct?

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.");
    }
}

3 Answers3

1

You should consider how use the this operator. In this website you can search for more information: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

See the next sample:

const test = {
  prop: 42,
  func: function() {
    return this.prop;
  },
};

console.log(test.func());
// expected output: 42

In this sample of code is used the function keyword so the this keyword can be used to access to the object fields. You should consider that each function called inside it can use the this operator to get the same object reference.

0

this inside the deposit function does not refer to the bank object, it refers to the window object, and this is because of the way the function is being called.

You can add a method inside the bank object which can call the deposit function which will make this refer to the bank object.

this is set based on the context. In the snippet below, the deposit function is being called in a similar manner but from a different context which sets this differently.

You should read more about how this works as mentioned in the comments.

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.");
    }
}

Or you can directly refer to the bank object.

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.");
    }
}
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
0

You need to call the function and set the context to the 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.`);
  }
}

A better alternative would be to use OOP and create a Bank object that can access and modify account balances.

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; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132