首页 > 解决方案 > 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);它时,两个属性都返回未定义,我做错了什么?

标签: javascript

解决方案


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


推荐阅读