2012-05-03 36 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