Javascript “this” losing context in IE

痞子三分冷 提交于 2019-12-12 13:34:50

问题


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.handleEvent);
        }
    }
}
HandleClick.prototype = {
    handleEvent: function(e) {
        alert(this);
    }
}
</script>
</head>
<body onload="new HandleClick('logo')"></body>
</html>

回答1:


.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 );
                                           } );
    }


来源:https://stackoverflow.com/questions/5198845/javascript-this-losing-context-in-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!