这旨在在浏览器上使用。
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”。如何在原型函数中引用对象的属性?