не удается получить доступ к свойству в coffeescript - PullRequest
1 голос
/ 24 октября 2011

Я намерен получить «0,0,0,0», но получу только «,,,».Похоже, мой способ доступа к свойству класса в coffeescript не работает должным образом.

class Tetris
    @array: []

    constructor: (@width, @height) ->
        @array = new Array(@width*@height)
        @array.map (item, i) -> this[i]=0

    to_s: ->
        array_item for array_item in this.array

$ ->
    t = new Tetris 2,2
    alert t.to_s()

Скомпилированный JavaScript-код выглядит следующим образом:

(function() {
  var Tetris;
  Tetris = (function() {
    Tetris.array = [];
    function Tetris(width, height) {
      this.width = width;
      this.height = height;
      this.array = new Array(this.width * this.height);
      this.array.map(function(item, i) {
        return this[i] = 0;
      });
    }
    Tetris.prototype.to_s = function() {
      var array_item, _i, _len, _ref, _results;
      _ref = this.array;
      _results = [];
      for (_i = 0, _len = _ref.length; _i < _len; _i++) {
        array_item = _ref[_i];
        _results.push(array_item);
      }
      return _results;
    };
    return Tetris;
  })();
  $(function() {
    var t;
    t = new Tetris(2, 2);
    return alert(t.to_s());
  });
}).call(this);

1 Ответ

2 голосов
/ 24 октября 2011

попробуйте

class Tetris
    constructor: (@width, @height) ->
        @array = for x in [ 0 ... (@height*@width)] then 0
        console.log @array
    to_s: ->
        array_item for array_item in this.array

$ ->
    t = new Tetris 2, 2
    alert t.to_s()

или это

class Tetris
    constructor: (@width, @height) ->
        @array = (0 for x in [0...(@height*@width)])
        console.log @array
    to_s: ->
        array_item for array_item in this.array

$ ->
    t = new Tetris 2, 2
    alert t.to_s()

Они оба генерируют один и тот же JavaScript

Это раздел, охватывающий понимание списка. http://jashkenas.github.com/coffee-script/#loops

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...