gpt4 book ai didi

javascript 函数调用不工作

转载 作者:行者123 更新时间:2023-12-02 14:38:09 24 4
gpt4 key购买 nike

我还在适应 JavaScript 的语法。我正在尝试将操作绑定(bind)到按键,但这里存在一些我无法发现的脱节。为什么 switch 案例可以毫无问题地被调用,但它调用的函数却永远不会执行?

this.init = function() {
$(document).keydown(this.handleKeyPress);
}

this.handleKeyPress = function(event) {
switch (event.which) {
case 37:
alert("key press"); //this executes
this.turn("left");
break;
case 38:
this.turn("up");
break;
case 39:
this.turn("right");
break;
case 40:
this.turn("down");
break;
}
}

this.turn = function(direction) {
alert(direction); //this does not
}

我认为这是唯一相关的代码,但如果有帮助,我很乐意发布更多内容。感谢您的帮助。

最佳答案

您很可能遇到了“this”含义的问题。当您位于匿名函数内部时, this 指的是匿名函数,而不是它嵌套的外部函数。您可能想要执行以下操作:

var myObj = this ;
myObj.init = function() {
$(document).keydown(myObj.handleKeyPress);
}

myObj.handleKeyPress = function(event) {
switch (event.which) {
case 37:
alert("key press"); //this executes
myObj.turn("left");
break;
case 38:
myObj.turn("up");
break;
case 39:
myObj.turn("right");
break;
case 40:
myObj.turn("down");
break;
}
}

myObj.turn = function(direction) {
alert(direction); //this does not
}

关于javascript 函数调用不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37261136/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com