How does the way in which a JavaScript event handler is assigned affect its execution?

后端 未结 4 734
予麋鹿
予麋鹿 2020-12-21 10:50

Please, consider the following code.


Question


        
4条回答
  •  执笔经年
    2020-12-21 11:37

    When the code is called from an on-event handler, its this is set to the DOM element on which the listener is placed:

    
    
    

    Note however that only the outer code has its this set this way. In this case, the inner function's this isn't set so it returns the global/window object (i.e. the default object in non–strict mode where this isn't set by the call).

    Check this in the global context and in function context.

    
    
    

    Another consideration is when you use addEventListener.

    Check event listener with an anonymous function and with an arrow function and this in arrow functions.

    Please note that while anonymous and arrow functions are similar, they have different this bindings. While anonymous (and all traditional JavaScript functions) create their own this bindings, arrow functions inherit the this binding of the containing context.

    
    
    
    

    Here is a simple article I wrote about the JavaScript this keyword but it doesn't mention event handler.

提交回复
热议问题