2013-08-21 24 views
0

爲什麼method1在init中直接工作,但在keyevent觸發時不起作用。 在32,39 keyevent它不起作用,但在keyevent 37它的作品。所以,該功能應該工作。javascript類對象,keyevent中的方法不起作用

init函數也有效,例如當我初始化method2,而方法運行時method1。這工作,但爲什麼當keyevent它不起作用?

function myClass() { 
    this.method1 = function method1(word) { 
     alert(word) 
    } 
    this.method2 = function method2(word) { 
     this.method1(word); 
    } 
    this.shortcutKey = function shortcutKey() { 
     document.onkeydown = function (event) { 
      if (event.keyCode == 32 || event.keyCode == 39) { 
       this.method1("undirect"); 
      } else if (event.keyCode == 37) {} 
     } 
    } 
    this.init = function init() { 
     this.method2("direct init"); 
     this.shortcutKey(); 
    } 
    this.init(); 
} 
var object = new myClass(); 
+3

'this'指的是「keydown」事件中的'document'。在設置'.onkeydown'之前,通過使用'var obj = this;'**之類的東西來存儲對'myClass'對象的引用。然後,在處理程序中,當您需要引用對象的方法時,請使用'obj.method1(「whatever」);' – Ian

+0

我避免省略分號以防止意外的自動插入。 –

回答

2

this關鍵字在不同的上下文中具有不同的值。

在回調this將必須可能參考window對象except in strict mode。當啓用嚴格模式時this將在undefined之外的對象上下文中。

問題是onkeydown事件沒有在MyClass的上下文中執行。爲了解決這個問題,你需要創建於預期的背景下,參考類似:

this.shortcutKey = function shortcutKey() { 
    var self = this; // create reference to context 

    document.onkeydown = function(event) { 
     if(event.keyCode==32 || event.keyCode==39) { 
      self.method1("undirect"); 
     } 
    } 
} 
+0

看來你可以刪除無用的'else if(event.keyCode == 37){}'部分,因爲它在這裏什麼都不做。 –

+0

@MarkSchultheiss感謝您的指針。清理了。 – Bart

+0

謝謝。完美的作品。 – fajarhac

1

查看控制檯,你會看到錯誤消息

TypeError: this.method1 is not a function [Break On This Error]

this.method1("undirect");

其原因誤差範圍界定。

範圍this指向錯誤的東西,您需要在keydown函數外引用this。看看調試語句,看看this實際上是什麼。

this.shortcutKey = function shortcutKey() { 
    var objScope = this; 
    document.onkeydown = function (event) { 
     if (event.keyCode == 32 || 
      event.keyCode == 39) { 
      console.log("this", this); /* this Window /_display/ */ 
      console.log("objScope", objScope); 
      objScope.method1("undirect"); 
     } else if (event.keyCode == 37) {} 
    } 
} 
+0

「看看調試語句,看看實際是什麼。」 感謝提示。真正有用的提示。 – fajarhac

0

當你調用

this.method1("undirect"); 

的 「本」 改變的範圍。它現在是指它是直接在功能 來指代「這個」你要引用,你必須把它先分配到一個臨時var,以使用範圍:

function myClass() { 
    this.method1 = function method1(word) { 
     alert(word) 
    } 
    this.method2 = function method2(word) { 
     this.method1(word); 
    } 
    this.shortcutKey = function shortcutKey() { 
     var that = this 
     document.onkeydown = function (event) { 
      if (event.keyCode == 32 || event.keyCode == 39) { 
       that.method1("undirect"); 
      } else if (event.keyCode == 37) {} 
     } 
    } 
    this.init = function init() { 
     this.method2("direct init"); 
     this.shortcutKey(); 
    } 
    this.init(); 
} 
var object = new myClass(); 
+0

[quote]「這個」的範圍改變了。 [/ quote] 謝謝。有用。 – fajarhac