Home > Web Front-end > JS Tutorial > body text

The this in the execution functions bound to addEventListener and attachEvent are different_Basic knowledge

WBOY
Release: 2016-05-16 17:47:12
Original
1035 people have browsed it

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:

Copy the code The code is as follows:


<

<Test

<

<

<


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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!