Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

console log event object shows different object properties than it should have

With below code I noticed that in the browser console when I log the event, the value for currentTarget logs null. However when I log e.currentTarget it logs a value. Any idea's on how that works?

var button = document.getElementById("btn");  var eventButtonHandler = function(e) {   var button = e.target;   console.log(e); // logs MouseEvent object with currentTarget:null   console.log(e.currentTarget); // logs a value   if(!button.classList.contains("active"))     button.classList.add("active");   else     button.classList.remove("active"); };  button.addEventListener("click", eventButtonHandler); 

A jsbin can be found here: http://jsbin.com/xatixa/2/watch?html,js,output

like image 496
Arjen de Vries Avatar asked Oct 21 '14 20:10

Arjen de Vries


People also ask

How do you display an object in console log?

Answer: Use console. log() or JSON. stringify() Method This method will print the object in browser console.

What function can be used with console log () to write objects to the console?

The console. log(JSON. stringify(obj)) method can be useful for logging the object to the console as string, as long as the data in the object is JSON-safe.

What does console log () do?

The console. log() is a function in JavaScript which is used to print any kind of variables defined before in it or to just print any message that needs to be displayed to the user. Syntax: console.


1 Answers

This is an artifact of the way the Javascript console works when you log an object. The log doesn't contain a copy of all the object properties, it just contains a reference to the object. When you click on the disclosure triangle, it then looks up all the properties and displays them.

In this case, at the time you call console.log(e), there's a DOM element in the currentTarget property. But sometime later, that property is reset to null for some reason. When you expand the event object, that's what you see.

A simple example that demonstrates this is:

var foo = { };  for (var i = 0; i < 100; i++) {      foo['longprefix' + i] = i;  }  console.log(foo);  foo.longprefix90 = 'abc';

When you view the object in the console, you'll see that foo.longprefix90 contains "abc", even though it contained 90 at the time that console.log(foo) was called.

The demonstration needs to use an object with lots of properties. When it's logging, it shows the first few properties that fit in the console, so those are in the early snapshot. Only properties after that display this anomalous behavior.

like image 168
Barmar Avatar answered Sep 21 '22 13:09

Barmar