最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.addEventListener('message', myFunction(event)) doesn't work - Stack Overflow

programmeradmin12浏览0评论

I'm trying to understand why the following does not work.

var myFunction = function(event) {
    // do something with event
};

window.addEventListener('message', myFunction(event));

I get the following error: "ReferenceError: event is not defined".

However, the following works and event is able to be used.

window.addEventListener('message', function(event) {
    // do something with event
});

How can I use event in the first situation? Why is event only accessible in the second situation?

I'm trying to understand why the following does not work.

var myFunction = function(event) {
    // do something with event
};

window.addEventListener('message', myFunction(event));

I get the following error: "ReferenceError: event is not defined".

However, the following works and event is able to be used.

window.addEventListener('message', function(event) {
    // do something with event
});

How can I use event in the first situation? Why is event only accessible in the second situation?

Share Improve this question asked Jan 21, 2016 at 1:19 iglvzxiglvzx 5081 gold badge8 silver badges22 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You are seeing the error because you are invoking the function immediately. You need to pass a reference to the function instead.

In other words, change this:

window.addEventListener('message', myFunction(event));

to this:

window.addEventListener('message', myFunction);

When using the addEventListener() method, the event object will be passed as the first parameter by default when the event is fired.

发布评论

评论列表(0)

  1. 暂无评论