Javascript:属性函数中的此引用
这是为了在浏览器上使用Javascript:属性函数中的此引用,javascript,function,this,prototype,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.fr
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”。如何在原型函数中引用对象的属性?试试这个
init : function () {
document.addEventListener("keydown", this.keyIsDown.bind(this));
document.addEventListener("keyup", this.keyIsUp.bind(this));
}
当您向函数传递引用时,this
不会神奇地绑定,在使用addEventListener()
的上下文中,this
就是它的本意
请注意,bind()
您可以填充它,传递在原型上调用您的函数的函数,或者使用具有绑定等效项的库(下划线中为..bind()
,jQuery中为$.proxy()
,等等)。试试这个
init : function () {
document.addEventListener("keydown", this.keyIsDown.bind(this));
document.addEventListener("keyup", this.keyIsUp.bind(this));
}
当您向函数传递引用时,this
不会神奇地绑定,在使用addEventListener()
的上下文中,this
就是它的本意
请注意,bind()
您可以对其进行填充,传递在原型上调用您的函数的函数,或者使用具有绑定等价物的库(下划线中为..bind()
,jQuery中为$.proxy()
,等等)。工作非常神奇!谢谢我将研究bind()函数,以便深入理解为什么它会起作用。@Dan我不知道为什么我选择了那个可怕的盗用词。谢谢你修好它。@DavidDaSilvaContín祝你好运,玩得开心!我会的!谢谢你解决了这个疑问:)像魔术一样工作!谢谢我将研究bind()函数,以便深入理解为什么它会起作用。@Dan我不知道为什么我选择了那个可怕的盗用词。谢谢你修好它。@DavidDaSilvaContín祝你好运,玩得开心!我会的!感谢您解答疑问:)