Javascript "this" playing context in IE

The following fine in Firefox / Safari / Chrome works, in IE "this" seems to lose the context of the handleEvent () function ... alert result: [Window object], which is not what I want; when the output from handleEvent (), "this" should be a reference to a HandleClick object, not a Window object.

Am I missing something basic that causes 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.handleEvent);
        }
    }
}
HandleClick.prototype = {
    handleEvent: function(e) {
        alert(this);
    }
}
</script>
</head>
<body onload="new HandleClick('logo')"></body>
</html>
+3
source share
1 answer

.attachEvent()does not give you thisas an element. You will need to wrap the handler in a function that calls 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 );
                                           } );
    }
+6
source

Source: https://habr.com/ru/post/1796385/


All Articles