LoginSignup
25

More than 5 years have passed since last update.

CoffeeScript のアンドキュメントな記法

Last updated at Posted at 2013-12-10

即時関数の引数に別名をつける

外部のスコープで宣言された変数を別名でスコープに取り入れる。

CoffeeScript
do ($ = jQuery) ->
  console.log $

コンパイルすると...

JavaScript
(function($) {
  return console.log($);
})(jQuery);

jQuery のプラグイン書くときとかに使う。

オブジェクトを作るショートハンド

変数名をキー名として取り入れる。

CoffeeScript
a = 3
b = true
c = 'bar'
console.log {a, b, c}   # { a: 3, b: true, c: 'bar' }

分解代入1で変数宣言

複数の変数を宣言する。

CoffeeScript
[ a, b, c ] = []

コンパイルすると...

JavaScript
var a, b, c, _ref;

_ref = [], a = _ref[0], b = _ref[1], c = _ref[2];

super を引数付きでコールする

super() ではなく super と書くことで引数を引き継いでコールしてくれる。

CoffeeScript
class Foo
  constructor: (@a) ->

class Bar extends Foo
  constructor: ->
    super

bar = new Bar 3
console.log bar.a  # => 3

便利な反面、super と書いた時点で継承元の関数が実行されることに気をつけなければならない。

CoffeeScript
class Foo
  func: ->
    console.log 'executed!!'
    'foo'

class Bar extends Foo
  func: ->
    @superFunc = super
    console.log @superFunc

bar = new Bar()
bar.func()  # => 'executed!!'
            # => 'foo'

このように super@superFunc に格納するつもりで書いたコードを実行すると、
super を実行した戻りが @superFunc に格納されることになる。

比較演算子

複数の条件をまとめて比較する。

CoffeeScript
a <= b < c

コンパイルすると...

JavaScript
(a <= b && b < c);

分解代入1とクラスの this 代入の合わせ技

CoffeeScript
class Foo
  constructor: ({@a})->

foo = new Foo {a: 3}
console.log foo.a   # 3

Array comprehensions とそのシュガー

配列を生成します。ここまではドキュメント通り。

CoffeeScript
countdown = (num for num in [10..1])

本末転倒気味だけど、括弧を書きたくない場合などは即時関数で書くことができる。

CoffeeScript
countdown = do -> num for num in [10..1]

引数の並置

CoffeeScript
# pattern1
a 1, 2, 3

# pattern2
a 1,
  2,
  3

# pattern3
a 1,
  2
  3

これらはコンパイルすると...

JavaScript
a(1, 2, 3);

pattern3 は使う気起きない。柔軟というよりは曖昧なコンパイラ。


  1. 分解代入については CoffeeScript - Destructuring Assignment - Qiita [キータ] を参照 

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
25