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

回答

1

尝试......

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

this当你传递给函数的引用没有神奇的约束,并在这方面与addEventListener(),该this是什么,就是要。

请注意,bind()不支持我们最喜欢的较老的IE浏览器。

您可以匀它,通过它呼吁原型的功能或使用具有绑定当量(_.bind()在下划线,$.proxy() jQuery的,等等),一库函数。

+0

工程像魔术!谢谢! 我将调查bind()函数,以深入理解为什么这会起作用。 –

+0

@丹我不知道我为什么选择那个可怕的挪用的词。感谢您修复它。 – alex

+0

@DavidDaSilvaContín祝你好运,玩得开心! – alex

相关问题