簡體   English   中英

Javascript:此引用在屬性函數中

[英]Javascript: this reference within a property function

旨在在瀏覽器上使用。

function keyboardJS () {
    this.keys = {};
    this.tempASCIIkey;
    this.tempCHARkey;
}
keyboardJS.prototype = {
    keyIsUp : function (evt) {
      console.log(this);
      this.ASCIIkey = evt.keyCode;
      this.CHARkey = String.fromCharCode(this.ASCIIkey);
      this.keys[this.CHARkey] = false;
      console.log(this.CHARkey + " is now " + this.keys[this.CHARkey]);
    },
    keyIsDown : function (evt) {
      console.log(this);
      this.ASCIIkey = evt.keyCode;
      this.CHARkey = String.fromCharCode(this.ASCIIkey);
      this.keys[this.CHARkey] = true;
      console.log(this.CHARkey + " is now " + this.keys[this.CHARkey]);
    },
    init : function () {
      document.addEventListener("keydown", this.keyIsDown);
      document.addEventListener("keyup", this.keyIsUp);
    }
}

var game = {};

game.myKeyboard = new keyboardJS();
game.myKeyboard.init();

但是,(console.log(this);)返回“ #document”。 如何在原型函數中引用對象的屬性?

嘗試這個...

init : function () {
  document.addEventListener("keydown", this.keyIsDown.bind(this));
  document.addEventListener("keyup", this.keyIsUp.bind(this));
}

當您傳遞對函數的引用時, this並沒有魔術般的綁定,在這種情況下,使用addEventListener()this就是它的本意。

請注意,我們最喜歡的舊版IE不支持bind()

您可以進行填充,傳遞在原型上調用函數的函數,或使用具有綁定等效項的庫(在_.bind()$.proxy()在jQuery中$.proxy()等)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM