控制台日志事件对象显示的对象属性与其应具有的对象属性不同 [英] console log event object shows different object properties than it should have

查看:48
本文介绍了控制台日志事件对象显示的对象属性与其应具有的对象属性不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码,我注意到在记录事件时在浏览器控制台中, currentTarget 的值记录为空。但是,当我登录 e.currentTarget 时,它会记录一个值。

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);

可以在这里找到jsbin: http://jsbin.com/xatixa/2/watch?html,js,output

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

推荐答案

这是记录对象时Javascript控制台工作方式的产物。日志不包含所有对象属性的副本,仅包含对对象的引用。当您单击显示三角形时,它将查找所有属性并显示它们。

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.

在这种情况下,在您调用控制台时.log(e) currentTarget 属性中有一个DOM元素。但是稍后,由于某种原因,该属性被重置为 null 。展开事件对象时,将看到此内容。

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';

当您在控制台中查看对象时,您会看到 foo.longprefix90 包含 abc ,即使它在调用 console.log(foo)时包含 90

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.

这篇关于控制台日志事件对象显示的对象属性与其应具有的对象属性不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆