2012-05-03 38 views
0

参考时,即时通讯按压空格键,铬示出了错误:“未捕获类型错误:对象#没有方法‘空格’”通对象方法,在Javascript

(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=""; 
} 

}

“this.submitMessage() “ChatManager的工作原理

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

当我在开始使用它时“this.KeyPress()”,ill get“undefined”;

IM试图避免多次switch语句和具有这样的功能对于这种情况下的JavaScript libaries .....

没有人知道哪里出错? 我得到的感觉,“this.spacebar”获取未定义的“this.submitMessage”,但初始化初始化ChatManager,并在初始化完成后按空格键...

(或不是有可能传递函数像我尝试过了?) %_%。

回答

1

这里的问题是与“本”关键字采取了不同的含义,当你进入功能this.KeyPress:

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

退房答案How does the "this" keyword work?更清晰的画面,但它看起来像你需要改变你的代码是这样的:

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;  
    }  
}  
+0

我从来没有想过这样的连接(哈哈...),谢谢:D – Hagorath