2011-10-24 7 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() 

コンパイルジャバスクリプトは次のようになります。

(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() 'の配列を指しません。マップ関数に '=>'を使用するとうまくいくでしょうが、iliaの方法が最適です:) –

答えて

2

は、彼らの両方が同じjavascriptの

を生成し、この

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() 

を試してみてください

これはリストの理解をカバーするセクションです。 http://jashkenas.github.com/coffee-script/#loops

+0

ありがとう!これは動作します!私のコードがうまくいかない理由を教えてください。私はCoffeescriptとJavascriptにはかなり新しいです。まだクラスと継承のニュアンスを学ぶのに苦労しています。 – lkahtz

+1

はArray.prototype.mapが定義されていますか? –

+0

私はREPLの下で試しました:コーヒー> [1,2,3] .map(item、i) - > this [i] = 0 私は[0、0、0]を得ることができます。 – lkahtz

関連する問題