实例化类时,“ this”为null

时间:2018-10-07 09:16:13

标签: javascript javascript-objects

我有两个文件 game.js board.js ,board.js看起来像这样

export default class Board {
  constructor() {
    this.islandTypes = ["atoll", "square", "s", "l", "dot"];
    this.state = this.freshState();
  }

  freshState() {
    let state = {};
    this.islandTypes.forEach(function (type) {
      state[type] = this.cleanIslandState();
    });
    return state;
  }

  cleanIslandState() {
    return {
      coordinates: [],
      hitCoordinates: []
    };
  }
}

和game.js看起来像这样

import Board from "./board.js";
(function(){
    playerBoard = new Board();
    //more stuff here
})();

我的问题是,在调用新的Board()时,Chrome在下面抛出错误

TypeError: Cannot read property 'cleanIslandState' of undefined

freshState的调用有效,但是cleanIslandState为什么失败?我缺少明显的东西吗?

0 个答案:

没有答案