简体   繁体   中英

Trying to understand the difference between passing 'this' vs. a reference to the event

I am trying to understand the differences between passing 'this' to a function versus passing a reference to the event itself.

I am testing with two separate divs and each has a separate function for mouseover and mouseout events. I pass just 'this' to one function and I pass both 'this' and 'e' to the other. My example is here: http://jsfiddle.net/jkolden/NQvaL/13/

document.getElementById('output').onmouseover = function(e) {mousein(e, this);};
document.getElementById('myDiv').onmouseover = function() {mouseinAlt(this);};

It seems as though the 'this' keyword is always going to refer to the html element to which I attach my listener, but 'e' will refer to the child of that html element is being moused over; is that a correct statement? I'm just curious if I am understanding this properly and if my example is using these in an appropriate manner.

this refers to the element to which you attached the event. e refers to the event object. Within that event object is a reference to the event's target (not always the same property in every browser, in IE it's srcElement ), which is the element on which the event was dispatched.

See more here: https://developer.mozilla.org/en-US/docs/Web/API/event.target

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM