-1

My code does not work correctly, I can not understand why. when you transfer the card to the shoop, he does not add money to it

   function Card (money=0) {
    this.money = money;
}

Card.prototype.addMoney = function(mon) {
  return this.money=this.money+mon;
}

 function CreditCard (money =0) {
this.money = money; 
}

 CreditCard.prototype = Object.create(Card.prototype);

function Shop (card) {
    this.card = card
    this.money=card.money;
    this.addMoney=this.card.addMoney;
}
Shop.prototype = Object.create(Card.prototype);


let card1 = new CreditCard(50);
card1.addMoney(10);//60
card1.addMoney(10);//70
let card2 = new Card(250);
let shop1 = new Shop(card1);
shop1.addMoney(10);//80 but don't work
console.log(card1.money);

2 Answers 2

1
this.addMoney = this.card.addMoney;

This is the line with the issue. The function internally references this.money, but since the function is now inside the Shop class, this changes to refer to the shop. So, you have to bind the function to the card. The new line would be:

this.addMoney = this.card.addMoney.bind(this.card);
Sign up to request clarification or add additional context in comments.

Comments

0

A shop is not a card. You should not use inheritance here. A shop has a card, so go for composition:

function Shop (card) {
    this.companyCard = card
}
Shop.prototype.addMoney = function(mon) {
    this.companyCard.addMoney(mon);
};
Shop.prototype.getMoney = function() {
    return this.companyCard.money;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.