记录事件对象时,currentTarget为null,但是在记录event.currentTarget时,它会记录一个值。这是为什么? [英] When logging an event object, currentTarget is null, but when logging event.currentTarget it logs a value. Why is that?

查看:163
本文介绍了记录事件对象时,currentTarget为null,但是在记录event.currentTarget时,它会记录一个值。这是为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用下面的代码我注意到,在我记录事件时,在浏览器控制台中,currentTarget的值记录为null。但是,当我记录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.

这篇关于记录事件对象时,currentTarget为null,但是在记录event.currentTarget时,它会记录一个值。这是为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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