如果在onkeypress之外调用killSwitch(),则会导致错误。
但是在onkeypress函数内部,我工作得很好。
为什么?

ojit_pre

最佳答案

您不能调用killSwitch,因为您已将方法定义为对象实例(this.killSwitch)的属性。

您不能在this事件中使用keypress,因为它将引用document,因此必须存储this值:

var ClassA = function() {
    var doc = document,
              instance = this; // store reference to `this`

    doc.onkeypress = function(e){ instance.killSwitch(); };
    this.killSwitch = function(){ alert('hello world'); };
}

var myClass = new ClassA();

10-07 19:35
查看更多