简体   繁体   English

Javascript:此引用在属性函数中

[英]Javascript: this reference within a property function

This is intended to use on the browser. 旨在在浏览器上使用。

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

However, (console.log(this);) returns "#document". 但是,(console.log(this);)返回“ #document”。 How do I reference the object's properties within a prototype function? 如何在原型函数中引用对象的属性?

Try this... 尝试这个...

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

The this isn't magically bound when you pass a reference to a function, and in this context with addEventListener() , the this is what it is meant to be. 当您传递对函数的引用时, this并没有魔术般的绑定,在这种情况下,使用addEventListener()this就是它的本意。

Note that bind() isn't supported by our favourite older IEs. 请注意,我们最喜欢的旧版IE不支持bind()

You can shim it, pass functions which call your functions on your prototype or use a library that has a bind equivalent ( _.bind() in Underscore, $.proxy() in jQuery, etc). 您可以进行填充,传递在原型上调用函数的函数,或使用具有绑定等效项的库(在_.bind()$.proxy()在jQuery中$.proxy()等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM