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