原型方法中的事件处理函数,为什么会认为.keyCode是JavaScript中未定义的属性? [英] Event Handler function in prototype's method, why does it think .keyCode is a property of undefined in JavaScript?

查看:49
本文介绍了原型方法中的事件处理函数,为什么会认为.keyCode是JavaScript中未定义的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试DOM事件处理程序,并将一个对DOM div元素起作用的函数放入了Constructor的原型中,该元素是由我的对象中的构造函数创建的属性.它正确显示了对象,但唯一不起作用的是它认为在我的方法 .keyCode 中,它是undefined的属性,并给我一个错误消息:

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:无法读取未定义的属性"keyCode"(函数KeyBlock.move中的第16行)

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));

这可能与方法中的参数 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";
}

推荐答案

您正在调用您的中的方法(带有未定义的 event 参数)addEventListener 调用,而不是传递.

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

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

应该是

addEventListener("keyup",me.move);

要访问您的 this 属性,您还需要 bind 该函数:

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

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

这篇关于原型方法中的事件处理函数,为什么会认为.keyCode是JavaScript中未定义的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆