CoffeeScriptの勉強 その3(オブジェクト)

Posted by Tatsuyano on Mon, Mar 11, 2013
In
Tags coffeescript

Objectの生成

this.x の代わりに @x と書くことができる

pos =
  x:100
  y:200
  dump: -> console.log "x:#{@x},y:#{@y}"

pos.dump()

コンパイル結果↓

var pos;
pos = {
  x: 100,
  y: 200,
  dump: function() {
    return console.log("x:" + this.x + ", y:" + this.y);
  }
};

一行で書く場合、「,」で区切る

size = width:100, height:200

コンパイル結果↓

var size;
size = {
  width: 100,
  height: 100
};

#### 配列 for .. in でループが書けます。
seq = ["a","b","c"]
for x in seq
  console.log x

 a
 b
 c

ループ中に配列のインデックスを拾いたい場合はforとinの間に2つ変数を置きます。

seq = ["a","b","c"]
for x,i in seq
  console.log "#{i} -> #{x}"
{% endcodeblock %}
0 -> a
1 -> b
2 -> c

#### 連想配列 for .. of を使って配列と同じように反復処理ができます。
data =
  x:100
  y:200

for key,value of data
  console.log "#{key} -> #{value}"

x -> 100
y -> 200

#### 存在チェック 変数名や関数名の直後に ? を付けると「その変数あるいは関数が定義されておりnull以外の値が入っているかどうか」をテストできます。
if myName?
  console.log "yes"
else
  console.log "no"

コンパイル結果↓

if (typeof myName != "undefined" && myName !== null) {
  console.log("yes");
} else {
  console.log("no");
}

また「.」や 「()」の前に ? を置くことで、変数や関数が存在する場合のみ処理を進めるようにできます。

console?.log?("Hello World")

コンパイル結果↓

if (typeof console != "undefined" && console !== null) {
  if (typeof console.log == "function") {
    console.log("Hello World");
  }
}

#### ヒアドキュメント
html = '''
aaa
bbb
ccc
'''

コンパイル結果↓

var html;
html = 'aaa\nbbb\nccc';

#### thisのバインド 関数定義時に -> の代わりに => を使うと、thisがバインドされて外側のthisを参照するようになります。
pos =
  x:100
  y:200
  dump: ->
    # 関数内部で@x(this.x)を使いたいのでfuncの定義は=>にしないといけない
    func = => console.log "x:#{@x}, y:#{@y}"
        func()

コンパイル結果↓

var pos;

pos = {
  x: 100,
  y: 200,
  dump: function() {
    var func,
    _this = this;
    func = function() {
      return console.log("x:" + _this.x + ", y:" + _this.y);
    };
    return func();
  }
};