将属性转移到对象方法中的事件函数中

transferring a property into an event function within an objects method

本文关键字:事件 函数 方法 对象 属性 转移      更新时间:2023-09-26

我试图采取一个对象属性,并将其转移到一个按键事件-麻烦的是,你只能添加事件本身,并使用这个。X_point在子函数中不起作用。这是我的代码。我也可以转移这个。X_point转换为var.x_point,然后使用它,但这完全破坏了它作为对象的意义。

function ninja(name, speed){
this.name = name;
this.speed = speed;
this.x_point = 0;
this.y_point = 0;
loadImages("n_main", 0, 0);
loadImages("n_armL", -5, 8);
loadImages("n_armR", 25, 8);

}

ninja.prototype.move = function(){
window.addEventListener("keydown", keyPress, false);
function keyPress(e){
    if(e.keyCode == 68){ //d
        alert(this.x_point);
    }
}

}

你可以使用bind:

ninja.prototype.move = function(){
window.addEventListener("keydown", keyPress.bind(this), false);
function keyPress(e){
    if(e.keyCode == 68){ //d
        alert(this.x_point);
    }
}

或者如果你使用jQuery,试试jQuery。代理(键盘按键,这)。

如果您使用that,例如:

ninja.prototype.move = function(){
 var that = this;
 window.addEventListener("keydown", keyPress, false);
 function keyPress(e){
  if(e.keyCode == 68){ //d
    alert(that.x_point);
 }
}