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
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With