Javascript“这个"在 IE 中丢失上下文 [英] Javascript "this" losing context in IE

查看:46
本文介绍了Javascript“这个"在 IE 中丢失上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我是否遗漏了导致 IE 出现这种情况的一些基本内容?

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>

推荐答案

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

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

这篇关于Javascript“这个"在 IE 中丢失上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆