Javascript "this" losing context in IE
The following works fine in firefox/safari/chrome, in IE, "this" appears to be losing context in the handleEvent() function...the result of the alert is [object Window], which is not what I want; when output from handleEvent(), "this" needs to be a reference to the HandleClick object, not the Window object.
Am I missing something basic which is causing this in IE?
<html>
<head>
<script type="text/javascript">
HandleClick = function(el) {
this.element = document.getElementById(el);
if( this.element.addEventListener ) {
this.element.addEventListener("click", this, false);
} else {
if( this.element.attachEvent ) {
this.element.attachEvent("onclick", this.handleEv开发者_StackOverflowent);
}
}
}
HandleClick.prototype = {
handleEvent: function(e) {
alert(this);
}
}
</script>
</head>
<body onload="new HandleClick('logo')"></body>
</html>
.attachEvent()
doesn't give you this
as the element. You'd need to wrap the handler in a function that invokes it from the context of the element to which it is attached.
if( this.element.attachEvent ) {
var that = this;
this.element.attachEvent("onclick", function() {
that.handleEvent.call( that.element );
} );
}
精彩评论