错误的上下文调用事件处理程序 [英] Event Handler Called With Wrong Context

查看:56
本文介绍了错误的上下文调用事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SomeObj 对象中,onkeydown事件处理程序 this.doSomething 在错误的上下文(文本框元素的上下文)中调用,但需要在错误的上下文中调用 this 的上下文.该怎么办?

In the SomeObj object, the onkeydown event handler this.doSomething is called in the wrong context (that of the textbox element) but it needs to be called in the context of this. How can this be done?

function SomeObj(elem1, elem2) {
    this.textboxElem = elem1;
    this.someElem = elem2;
    this.registerEvent();
}

SomeObj.prototype = {
    registerEvent: function() {
        this.textboxElem.onkeydown = this.doSomething;
    },
    doSomething: function() {
        // this must not be textboxElem
        alert(this);
        this.someElem.innerHTML = "123";
    }
};

推荐答案

将引用复制到局部变量,以便可以在闭包中使用它:

Copy the reference to a local variable, so that you can use it in a closure:

registerEvent: function() {
  var t = this;
  this.textboxElem.onkeydown = function() {
    t.doSomething();
  };
},

这篇关于错误的上下文调用事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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