2011-10-24 2 views
1

"0,0,0,0"을 얻으 려하지만 ",,,"만 얻으려고합니다. coffeescript의 내 접근 방법 속성이 제대로 작동하지 않는 것 같습니다.coffeescript에서 속성에 액세스하지 못했습니다.

(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

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

그들은 모두 같은 자바 스크립트

을 생성하려고 다음과 같이

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

컴파일 된 자바 스크립트입니다

이것은 목록 이해력을 다루는 섹션입니다. 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

관련 문제