CoffeeScriptを書いてみる その1
前回、CoffeeScriptの環境を作ったので、
早速書き始めてみようと思います。
今回のテーマ
- 関数定義
- 文字列内変数展開
関数定義
CoffeeScriptでの関数定義はこんな感じになるようです。
helloworld.coffee
helloworld = -> console.log "hello world"
呼び出してみます。
helloworld()
実行
$ coffee helloworld.coffee hello world
引数がある関数を定義してみます。
square.coffee
square = (x) -> x * x console.log square(10)
実行
$ coffee square.coffee 100
関数呼び出す時に、引数は括弧なしでも呼び出せるっぽい??
ちょっと試してみます。
hoge.coffee
hoge = (x,y) -> x + y console.log hoge 1, 2
実行
$ coffee hoge.coffee 3
括弧なしでも呼び出せるっぽい、ですね。
もう一発試してみます。
hoge2.coffee
hoge = (x,y) -> x + y hoge2 = (x,y,z) -> x + y + z console.log hoge 1, hoge2 2, 3, 4
実行
$ coffee hoge2.coffee 10
おぉ、できた、なるほど。
では、引数なしの場合も括弧は省略できるんでしょうか?
CoffeeScriptはRuby+Pythonライクらしいので、
Rubyライクであればできるだろうし、Pythonライクであれば関数オブジェクトが返ってくるのかな?
やってみます。
function.coffee
f = -> "called" console.log f
実行
$ coffee function.coffee [Function]
なるほど、関数オブジェクトが返ってくるっぽい。
以下のように変更して実行してみます。
f = -> "called" console.log f console.log f() console.log f.call()
実行
$ coffee function.coffee [Function] called called
こうなるんですね、なるほど。
では、このcoffeeファイルをJavaScriptにコンパイルしてみましょう。
$ coffee -c function.coffee
コンパイルするときは、「-c」をつけて実行します。
結果
// Generated by CoffeeScript 1.4.0 (function() { var f; f = function() { return "called"; }; console.log(f); console.log(f()); console.log(f.call()); }).call(this);
大体予想どおりではありました。
ちなみに、
var f; f = function() { return "called"; };
これは、
var f = function() { return "called"; }
こうならないのは何故なんでしょう?
前者のほうが効率が良いんでしょうか?
JavaScriptの言語仕様に詳しくないので、理由はわかりませんでした。。。
文字列内変数展開
CoffeeScriptはRubyのように文字列リテラル内で変数展開ができるようです。
試してみます。
string_interpolation.coffee
i = 1 console.log "hoge #{i} foo"
実行
$ coffee string_interpolation.coffee hoge 1 foo
構文はRubyまんまですね。
では、Rubyみたいに式展開はできるのでしょうか?
i = 1 console.log "hoge #{i + 100} foo"
実行
$ coffee string_interpolation.coffee hoge 101 foo
おぉー、できるんですね。なるほど。
関数呼び出しもできるのかな?
f = -> "aaaaaaaaa" console.log "hoge #{f()} foo"
実行
$ coffee string_interpolation.coffee hoge aaaaaaaaa foo
まぁあたりまえか。できますよね。
では、こいつもコンパイルしてみましょう。
i = 1 console.log "hoge #{i} foo" console.log "hoge #{i + 100} foo" f = -> "aaaaaaaaa" console.log "hoge #{f()} foo"
string_interpolation.js
// Generated by CoffeeScript 1.4.0 (function() { var f, i; i = 1; console.log("hoge " + i + " foo"); console.log("hoge " + (i + 100) + " foo"); f = function() { return "aaaaaaaaa"; }; console.log("hoge " + (f()) + " foo"); }).call(this);
なるほど、文字列連結になるんですね。
というわけで、今日はここまで。
(もうちょっと仕様を深く知りたいなぁ)