2011-10-24 105 views
1

我打算獲得「0,0,0,0」但只獲得「,,,」。這似乎是我在coffeescript中訪問類屬性的方式無法正常運行。無法訪問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); 
+0

'this'不指向'map()'中的數組。如果你使用'=>'作爲map函數,它可能會工作,但是ilia的方法最好:) –

回答

2

試試這個

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

+0

謝謝!這工作!你能告訴我爲什麼我的代碼不工作嗎?我對Coffeescript和Javascript很新。仍然努力學習階級和繼承的細微差別。 – lkahtz

+1

是否定義了Array.prototype.map? –

+0

我嘗試了REPL:coffee> [1,2,3] .map(item,i) - > this [i] = 0 我可以得到[0,0,0]。 – lkahtz