javascript 控制台日志事件对象显示的对象属性与其应有的属性不同
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26496176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
console log event object shows different object properties than it should have
提问by Arjen de Vries
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?
使用下面的代码,我注意到在浏览器控制台中,当我记录事件时,currentTarget
记录的值为 null。但是,当我记录e.currentTarget
它时,它会记录一个值。关于它是如何工作的任何想法?
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
jsbin 可以在这里找到:http://jsbin.com/xatixa/2/watch?html,js,output
回答by Barmar
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.
这是记录对象时 Javascript 控制台工作方式的产物。日志不包含所有对象属性的副本,它只包含对对象的引用。当您单击显示三角形时,它会查找所有属性并显示它们。
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.
在这种情况下,在您调用 时console.log(e)
,currentTarget
属性中有一个 DOM 元素。但过了一段时间,null
由于某种原因,该属性被重置为。当您展开event
对象时,这就是您所看到的。
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.
当您在控制台中查看对象时,您会看到foo.longprefix90
contains "abc"
,即使它90
在console.log(foo)
被调用时包含。
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.
演示需要使用具有很多属性的对象。记录时,它会显示适合控制台的前几个属性,因此这些属性位于早期快照中。只有在此之后的属性才会显示这种异常行为。