javascript - javascript中方法内部的未定义属性
问题描述
我正在尝试在 javascript 中使用 OOP 构建一个简单的启动画面。我想创建一个允许用户循环浏览游戏菜单的代码,但我偶然发现了一个错误。我试图访问方法this.state, this.selection
内部,control()
但它们都返回 undefined,即使它们都在constructor()
类的函数中声明。这是我的一些代码
class Game {
constructor() {
this.menu = ['Start', 'Load', 'Exit'];
this.selection = 1;
this.canvas = document.getElementById('game');
this.ctx = this.canvas.getContext('2d');
this.state = 'menu';
window.addEventListener('keydown', this.control, false);
this.splash();
}
control(e) {
console.log(e.keyCode);
console.log(this.state, this.selection);
if (this.state == 'menu') {
console.log('true');
splash(e.keyCode);
} else {
return e.keyCode;
}
}
splash(key) {
console.log('successfully initialized');
if (key == 38) {
this.selection--;
console.log(this.menu[this.selection]);
} else if (key == 40) {
this.selection++;
console.log(this.menu[this.selection]);
}
}
}
var game = new Game;
当我使用console.log(this.state, this.selection);
它时,两个属性都返回未定义,我做错了什么?
解决方案
问题在于this
事件处理程序内部不再涉及您的游戏实例。您可以使用bind(this)
.
另一个问题是您this
在调用splash
. 我也在下面的示例中修复了这个问题。
class Game{
constructor(){
this.menu = ['Start', 'Load', 'Exit'];
this.selection = 1;
this.canvas = document.getElementById('game');
//this.ctx = this.canvas.getContext('2d');
this.state = 'menu';
window.addEventListener('keydown',this.control.bind(this),false);
this.splash();
}
control(e){
console.log(e.keyCode);
console.log(this.state, this.selection);
if(this.state == 'menu'){
console.log('true');
this.splash(e.keyCode);
}else{
return e.keyCode;
}
}
splash(key){
console.log('successfully initialized');
if(key == 38){
this.selection--;
console.log(this.menu[this.selection]);
}else if(key == 40){
this.selection++;
console.log(this.menu[this.selection]);
}
}
}
var game = new Game();
<div id="game"></div>
推荐阅读
- routing - Typo3 9 - 路由 - 新闻列表中的 cHash
- javascript - 如何阻止导航栏干扰模式关闭按钮的功能?
- android - 无法解析符号 AppCompatActivity
- c++ - 当我尝试删除指针时我的程序崩溃了
- c++ - 从本机 C++ 结构构建时是否可以优化 flatbuffers 序列化?
- php - 为什么我的 crontab 不在服务器中运行我的电报机器人 php 代码?
- excel - 在宏中查找excel表的最后一行和最后一列
- json - MongoDB查询过滤对象数组和格式返回对象
- r - 如何在 R 中修复大型数据框
- reactjs - 向 Redux 存储添加嵌套数组项时未定义 this.props.onPress(row)