0

I am wildly confused by Javascript's ability to handle events out of order. On windows/chrome, the code below outputs to console the object with the class already changed before it has been changed, but then outputting just the class shows the unchanged class. Can someone please explain what rule is governing this? I don't know how to anticipate in what state to expect to see my objects.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Table Schema</title>
</head>

<body>
  <a href="#" class="first_class" onclick="checkClass(this)">I am supposed to be first_class!</a>
  <script>
    function checkClass(obj) {
      console.log(obj);
      console.log(obj.className);
      if (obj.className == 'first_class') {
        obj.className = 'second_class';
      }
    }
  </script>
</body>

</html>
<html>
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
  • says first class for me with the string and an obj show the up to date value not the snapshot at that moment in time. https://stackoverflow.com/questions/30150469/why-console-log-displays-incorrect-objects-values – epascarello Oct 06 '17 at 13:07

1 Answers1

0

The value of obj is a reference to an object.

The value of obj.className is a string, and then it is a different string.

Some consoles are asyncronous. If they are rendering an object, then the data in the object changes, you will see the updated data.

There is no way for a string to change, strings are immutable, so if you pass a string, the the asyncronisity doesn't matter.

If you want to avoid seeing the updated object, see this question.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks @Quentin, that is helpful. I'll look into whether I can pass just the string in my use-case. Is there a way to output objects more reliably? – Robyn Wyrick Oct 06 '17 at 13:12
  • @RobynWyrick — See the last sentence of the answer. – Quentin Oct 06 '17 at 13:17
  • thanks. Followed the link and that should work. I have to agree with Mikulas, I can't think of any situation this behavior of the console would be preferred, from a programmer's point of view. – Robyn Wyrick Oct 06 '17 at 13:23