Javascript:属性函数中的引用

Javascript: this reference within a property function

本文关键字:引用 函数 属性 Javascript      更新时间:2023-09-26

这是在浏览器上使用的。

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();

但是,(控制台.log(这);)返回"#document"。如何在原型函数中引用对象的属性?

试试这个...

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

当你传递对函数的引用时,this不会神奇地绑定,在这个上下文中,addEventListener()this就是它的意思。

请注意,我们最喜欢的旧IE不支持bind()

你可以填充它,传递在原型上调用你的函数的函数,或者使用具有绑定等效项的库(在下划线中_.bind(),在jQuery中$.proxy()等)。