无法输入CoffeeScript for循环

时间:2013-07-01 01:55:10

标签: for-loop foreach scope coffeescript range

为什么我的代码没有到达包含alert的行?

window.Game = class Game
  constructor: ->
    rows: 22
    columns: 10
    board: []

createBoard: ->                                                                                                                                                                                           
  # Some code here...
  for x in [0...@columns]
    alert("THIS IS HERE")
  # More code down here...

1 个答案:

答案 0 :(得分:2)

可能是因为@columnsundefined

你的构造函数:

constructor: ->
  rows: 22
  columns: 10
  board: []

只需创建一个对象并将其抛弃,它与此相同:

constructor: ->
  o = {
    rows: 22
    columns: 10
    board: []
  }
  return

因此,没有设置实例变量,您的构造函数根本没有做太多。也许你想说:

constructor: ->
  @rows = 22
  @columns = 10
  @board = []

或可能:

constructor: (@rows = 22, @columns = 10, @board = [ ]) ->

我假设您的createBoard方法实际上缩进了一个级别,因此它是Game类中的方法。