1
这是为了在浏览器上使用。Javascript:此属性函数中的引用
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”。如何在原型函数中引用对象的属性?
工程像魔术!谢谢! 我将调查bind()函数,以深入理解为什么这会起作用。 –
@丹我不知道我为什么选择那个可怕的挪用的词。感谢您修复它。 – alex
@DavidDaSilvaContín祝你好运,玩得开心! – alex