javascript - addEventListen passes this into the second parameter to implement binding events
怪我咯
怪我咯 2017-05-18 11:03:11
0
2
923

Recently I was looking at the source code implementation of some libraries, and I discovered that this was passed into the second parameter of addEventListener. I felt confused, so I came up to ask questions. The following code is what I simply simplified and passed the test

    <script>
        this.onclick=function(){
            console.log('onclick');
        }
        app.addEventListener('click',this);
    </script>

Why can events be bound in this way?

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
小葫芦

The

addEventListener的第二个参数可以传一个对象,当事件触发时,这个对象的handleEvent method is called like this:

document.body.addEventListener(
    'click',
    {
        handleEvent: function() {
            alert('body clicked');
        }
    },
    false);

Reference:
handleEvent of the second parameter of addEventListener
http://peter.michaux.ca/artic...
MDN

習慣沉默

Are you sure this addEventListener is the native JS window.addEventListener?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template