问题
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