Event Handler function in prototype's method, why does it think .keyCode is a property of undefined in JavaScript?

大憨熊 提交于 2019-12-12 01:54:15

问题


I am experimenting with DOM event handlers, and I put in my Constructor's prototype a function that works on the DOM div element, which is a property created by the constructor in my object. It displays the object correctly, but the only thing that does not work is that it thinks that in my method, .keyCode, is a property of undefined and gives me an error message:

TypeError: Cannot read property 'keyCode' of undefined (line 16 in function KeyBlock.move)

This is my method, along with my calling of it:

  KeyBlock.prototype.move = function(event) {
  if(event.keyCode == 37)
    this.x -= 1;
  if(event.keyCode == 38)
    this.y -= 1;
  if(event.keyCode == 39)
    this.x += 1;
  if(event.keyCode == 40)
    this.y += 1;
  if (this.y < 0)
    this.y = 0;
  if (this.x < 0)
    this.x = 0;
  console.log(this.y);
}
me = new KeyBlock("me");
addEventListener("keyup", me.move(event));

It might have to do with the argument, event, in the method? To answer this question, my constructor itself will not be needed, but I will also place it (below this text), to make clear what I am doing.

  var KeyBlock = function(name) {
  this.character = document.createElement("div");
  document.body.appendChild(this.character);
  this.character.style.width = "20px";
  this.character.style.height = "20px";
  this.name = name;
  this.x = 0;
  this.y = 0;
  this.character.style.background = "indigo";
  this.character.id = this.name;
  this.character.style.left = String(this.x) + "px";
  this.character.style.top = String(this.y) + "px";
}

回答1:


you're calling your method(with a not defined event argument) in your addEventListener call instead of passing it.

addEventListener("keyup", me.move(event));

should be

addEventListener("keyup", me.move);

to have access to your this property you need to bind the function aswell:

addEventListener("keyup", KeyBlock.prototype.move.bind(me));



来源:https://stackoverflow.com/questions/27681939/event-handler-function-in-prototypes-method-why-does-it-think-keycode-is-a-pr

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!