Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's 'this' in IE's attachEvent

I'm tired of writing jQuery, so I decide to learn some raw JavaScript. Something in IE's attachEvent confused me. Here's the code:

var btn = document.getElementById('myBtn');
    
btn.onclick = function(){
   alert(window.event.srcElement === this); //true, I know why.
};
        
btn.attachEvent('onclick', function(event){
   alert(event.srcElement === this); //fasle, but why?
});

I try to use IE's built-in debug tools, but it just told me that 'this' is an object, but nothing more... so what's 'this' in IE's attachEvent?

like image 205
shawjia Avatar asked Feb 09 '12 02:02

shawjia


1 Answers

Within an event handler bound by the IE-specific attachEvent method, this refers to the global window object:

btn.attachEvent('onclick', function(event) {
    alert(this === window); // true
}

In contrast, within an event handler bound by the standard addEventListener method, this refers to the DOM element from which the event handler was triggered.

like image 181
Michael Liu Avatar answered Sep 27 '22 23:09

Michael Liu