For example, what is the difference between <td id='xyz' onmouseover='doIt(this)'...
and <td id='xyz' onmouseover='doIt()'...
. Is this
the DOM element?
Browsers invoke constructed handler functions such that this
refers to the DOM element targeted by the event. Thus, this
is just a reference to the DOM element on which such an attribute appears.
In the example, this
refers to the DOM element the handler is bound to. I recommend to read the excellent articles at quirksmode.org , which explains this and much more about event handling.
what is the difference between
<td id='xyz' onmouseover='doIt(this)'...
and<td id='xyz' onmouseover='doIt()'...
In the first case you are passing an argument to the function, which is a DOM element, in the second case you don't.
The this
will refer to the DOM element, in your example the td
DOM element.
Have a look at the MDN page on event handlers for more information, specifically the section on inline event handlers .
You asked "what is the difference". The difference is that in the first case, the call is made from an execution context where this
is a reference to the element and that reference is passed to doIt
as the first parameter. In the second case no parameters are passed.
Now the why.
When an event reaches an element, the related handler will see if there is any code to run. If there is, it will create a new execution context as if in function code with the global object on its scope chain and this
binding set to the element. It will then execute the code. So within the execution context of the handler, when the code:
doIt(this)
is executed, this
references the element. Note that since this
is not set in the call to doIt()
, its this
will either default to the global object in non–strict mode, or remain undefined in strict mode.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.