javascript event 是一个全局变量,可以在回调链中随处访问吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6426497/
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
is event a global variable that is accessible everywhere inside the callback chain?
提问by zanona
I was just playing around with event listeners with DOM and javascript and did notice this:
我只是在玩带有 DOM 和 javascript 的事件侦听器,并且确实注意到了这一点:
function chained(msg) {
console.log(msg, event);
}
function onClick() {
chained('the body was clicked');
}
document.body.addEventListener('click', onClick);
Now the funny thing...this will output:
现在有趣的是......这将输出:
"the body was clicked, (MouseEvent)"
“身体被点击,(MouseEvent)”
Then I ask, why? how does it passes the event object without sending it on the chained
call?
那我问,为什么?它如何传递事件对象而不在chained
调用时发送它?
function chained(msg) {
console.log(msg, namedEventObj); //throw error namedEventObj is not defined
}
function onClick(namedEventObj) {
console.log(event); //outputs (MouseEvent);
console.log(nameEventObj); //outputs (MouseEvent);
chained('the body was clicked');
}
document.body.addEventListener('click', onClick);
Even If I declare the event obj to be passed on the onClick
function as namedEventObj
it will available only to onClick
but not to chained
function...I got this and this makes sense for me...but definitely not the event
variable to be available to the chained
function.
即使我声明将事件 obj 传递给onClick
函数,因为namedEventObj
它只能用于onClick
但不能用于chained
函数……我明白了,这对我来说很有意义……但绝对不是函数event
可用的变量chained
。
Anyone know why does it behaves like this?
有谁知道它为什么会这样?
The only thing I can think of is that event is in fact window.event
and it makes itself available when some event dispatches and Event...but that would mean that any element could get that event information if called at the same time as the event when it triggers?
我能想到的唯一一件事是事件实际上是window.event
并且它在某些事件调度和事件时使自己可用......但这意味着任何元素都可以在与事件同时调用时获取该事件信息触发器?
I am using Chrome 11.0.x
我正在使用 Chrome 11.0.x
回答by Nathan Romano
One can access the current event through window.event
. Just using event
is implicitly accessing window.event
.
可以通过 访问当前事件window.event
。仅使用event
就是隐式访问window.event
.