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

后端 未结 1 377
暗喜
暗喜 2020-12-23 18:34

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

相关标签:
1条回答
  • 2020-12-23 18:58

    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.

    0 讨论(0)
提交回复
热议问题