Using this inside an event handler

后端 未结 2 2243
执笔经年
执笔经年 2020-11-27 06:56

I was trying to find the meaning of this keyword inside event handler function in the DOM level 3 event spec.

As per my experiment this ref

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 07:44

    In an event handler for an element, with default capturing (false), this will refer to the element which detected the event. Either one may be used.

    For example:

    element.addEventListener('keydown', function (event) {
        // `this` will point to `element`
    }, false);
    

    When capturing an event (true), say at the window level, event.target, will refer to the element which originated the event, while this will refer to the capturing element. For example:

    window.addEventListener("error", function (event) {
        event.target.src = 'some_path';
        // `this` will point to window
        // `event.target` will point to the element that had an error
    }, true);
    

    I hope this exemplifies the difference between each.

提交回复
热议问题