Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

trouble with updating my object

Tags:

Hello I am pretty new at JavaScript and I am a little stuck right now. The point of the project I'm doing is to create a card object and have methods that set a new face and suit. When I click the button to show my card it works however when I click the button to update my face and suit and reclick the button to show my card it doesn't show the updated info. I've been on this for quite a while now and still don't understand why it doesn't work. PLS HELP :)

<!DOCTYPE html>
<html>

<head>
  <title>Object Oriented Programming</title>
  <script>
    function Card(suit, face) {
      this.suit = suit;
      this.face = face;
      this.card = face + ' of ' + suit;
      this.showCard = function() {
        alert(this.card);
      }
      this.setSF = function(newSuit, newFace) {
        this.suit = newSuit;
        this.face = newFace;
      }
    }

    var card1 = new Card("Diamonds", 8);
  </script>
</head>

<body>
  <input type="button" value="Show card" onclick="card1.showCard()" />
  <input type="button" value="Click to change the suit and face" onclick="card1.setSF('Hearts',5)" />

</body>

</html>
like image 230
codenoob Avatar asked Jun 18 '18 01:06

codenoob


People also ask

How to update object in state?

To update an object in a state array, call the map() method to iterate over the array and update the object that matches the condition. Copied! const updateObjectInArray = () => { setEmployees(current => current.

How to update the object value in React?

To update an object in an array in React state: Use the map() method to iterate over the array. On each iteration, check if a certain condition is met. Update the object that satisfies the condition and return all other objects as is.

How to change object in state React native?

Changing the state Object To change a value in the state object, use the this. setState() method.


1 Answers

You are close. It's because you aren't updating this.card when you set the new card. So instead of alerting this.card, just alert this.face + ' of ' + this.suit which you did update, and remove this.card all together as it isn't really doing anything and is redundant.

<!DOCTYPE html>
<html>

<head>
  <title>Object Oriented Programming</title>
  <script>
    function Card(suit, face) {
      this.suit = suit;
      this.face = face;
      this.showCard = function() {
        alert(this.face + ' of ' + this.suit);
      }
      this.setSF = function(newSuit, newFace) {
        this.suit = newSuit;
        this.face = newFace;
      }
    }

    var card1 = new Card("Diamonds", 8);
  </script>
</head>

<body>
  <input type="button" value="Show card" onclick="card1.showCard()" />
  <input type="button" value="Click to change the suit and face" onclick="card1.setSF('Hearts',5)" />

</body>

</html>
like image 180
Jordan Soltman Avatar answered Sep 28 '22 18:09

Jordan Soltman