Javascript:属性函数中的这个引用

时间:2012-05-23 12:12:26

标签: javascript function this prototype

这是打算在浏览器上使用。

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”。如何在原型函数中引用对象的属性?

1 个答案:

答案 0 :(得分:1)

试试这个......

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

当您传递对函数的引用时,this不会被神奇地绑定,并且在{(1}}的上下文中,addEventListener()就是它的意图。

请注意,我们最喜欢的旧版IE不支持this

您可以对其进行填充,传递在原型上调用函数的函数,或者使用具有等效绑定的库(在Underscore中为bind(),在jQuery中为_.bind()等)。