0

当我按下空格键时,chrome 显示错误:“未捕获的类型错误:对象 # 没有方法‘空格键’”

(firefox 确实说“this.Spacebar 不是函数”);

这是对象,它将由“Init();”初始化 (在页面加载...):

function KeyManager() { 
this.mode="none";

this.Spacebar = ChatManagement.submitMessage;
this.KeyPress = function(e) {
        if(e.keyCode==13) {
            this.Spacebar();
        }
    }
this.switchKeySet= function(value) {
    if(this.mode!=value) {
        this.mode=value;
        switch(value) {
            case "login":
            this.Spacebar = LoginManagement.SendLogin;
            break;
            case "chat":
            this.Spacebar = ChatManagement.submitMessage;
            break;              
            default:
            case "none":
            break;
        }
    document.onkeypress=this.KeyPress;
    }
}

初始化函数:

function Init() {
ChatManagement = new ChatManager();
LoginManagement= new Login();
KeyManagement= new KeyManager();
KeyManagement.switchKeySet("chat");
}

聊天管理对象:

function ChatManager() {
this.submitMessage = function() {
    $("Message").focus();
    var text = $("Message").value; 
    if(text==""){  
        this.write('<p class="warning">Please enter a message');  
        return;  
    }  
    try{ 
        SendMessage(text);  
        this.write('<p class="event">Sent: '+text)  
    } catch(exception){  
    this.write('<p class="warning"> Error:' + exception);  
    } 
    $("Message").value="";
}

}

ChatManager 的“this.submitMessage()”有效

当我使用“console.log(this.Spacebar);” “switchKeySet();”的末尾 我得到“this.submitMessage()”的代码。

当我在“this.KeyPress()”开始时使用它时,会得到“未定义”;

我试图避免多个 switch 语句和 javascript-libaries 对这种情况有一个功能.....

有人知道错误在哪里吗?我有感觉,“this.spacebar”得到了未定义的“this.submitMessage”,但初始化首先初始化ChatManager,然后在初始化完成后按空格键......

(或者不能像我尝试的那样传递函数吗?) %_%.

4

1 回答 1

1

这里的问题是,当您进入 this.KeyPress 的函数时,“this”关键字具有不同的含义:

this.Spacebar = ChatManagement.submitMessage; // 'this' refers to the KeyManager function 
this.KeyPress = function(e) { 
        if(e.keyCode==13) { 
            this.Spacebar(); // 'this' refers to the caller of the function (keypress event)
        } 
    } 
 ....
    document.onkeypress=this.KeyPress;  
  }

查看“this”关键字如何工作的答案?为了获得更清晰的图片,但看起来您需要将代码更改为:

function KeyManager() {
var self = this;      
self.mode="none";     

self.Spacebar = ChatManagement.submitMessage;     
self.KeyPress = function(e) {     
        if(e.keyCode==13) {     
            self.Spacebar();     
        }     
    }     
self.switchKeySet= function(value) {     
    if(self.mode!=value) {     
        self.mode=value;     
        switch(value) {     
            case "login":     
            self.Spacebar = LoginManagement.SendLogin;     
            break;     
            case "chat":     
            self.Spacebar = ChatManagement.submitMessage;     
            break;                   
            default:     
            case "none":     
            break;     
        }     
    document.onkeypress=self.KeyPress;     
    }     
}     
于 2012-05-03T04:56:35.803 回答