Javascript"这个"在IE中丢失了上下文

aha*_*blu 3 javascript prototype this

以下在firefox/safari/chrome中工作正常,在IE中,"this"似乎在handleEvent()函数中丢失了上下文...警告的结果是[object Window],这不是我想要的; 当从handleEvent()输出时,"this"需要是对HandleClick对象的引用,而不是Window对象.

我错过了一些在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>
Run Code Online (Sandbox Code Playgroud)

use*_*716 6

.attachEvent()没有给你this作为元素.您需要将处理程序包装在一个函数中,该函数从它所附加的元素的上下文中调用它.

    if( this.element.attachEvent ) {
        var that = this;
        this.element.attachEvent("onclick", function() { 
                                              that.handleEvent.call( that.element );
                                           } );
    }
Run Code Online (Sandbox Code Playgroud)