There are many blog posts about the difference between addEventListener and attachEvent, but most of them focus on the fact that the former is Firefox chrome, and the latter only exists in the IE series.
When I was writing an event proxy recently, I encountered a BUG. I found that in addition, the this in the execution functions bound to the two are different. The context of the addEventListener and attachEvent functions at runtime are different. Same.
A simple demo is used to describe this difference:
Click test1 First alert under chrome: " a1", the second alert: "undefined"
The first alert in firefox: " a1", the second alert: " undefined"
The first alert in IE: " a1", the second time Alert: "undefined"
This is easy to understand. At this time, this points to the DOM #a1, so the alert id is the id "a1" of #a1. Then in this, there is no variable testGolb, so it is undefined.
Click test2 The first alert under chrome: "a1", the second alert: "undefined"
The first alert under firefox: "a1", the second time alert :"undefined"
The first alert in IE:" undefined", the second alert :"diff"
Chrome and Firefox behave the same when clicking test1, but IE is different . When using attachEvent to bind an event, this in the function points to the window, not the dom where the event is added, so the first alert value is undefined, and the value of this.testGlob is diff.