woshidan's loose leaf

ぼんやり勉強しています

Coffee Script入門した

ドットインストールでcoffee script入門やってた。 http://coffeescript.org/ の TRY COFFEESCRIPT のタブで試しながら打てる。

メモ。

コメント

# comment for 1 line

###

  comment for multiple line

###

生JSと違うところ

  • var は書く必要がない(というよりreserved wordとして書けない)
  • ; いらない
  • {} rubyらしいブロックを使う
  • () 曖昧性が無い場合は省略可.
  • "#{string_var}" で文字列展開が出来る

条件分岐

# ruby
input = 1

case input
when 1, 10
  puts input
when 2 then puts input
else
  puts input
end
# coffee
input = 1

switch input
  when 1, 10
    console.log input
  when 2 then console.log input
  else
    console.log input
# 複数行

msg = "this
is
a very
long
msg"

# インデントしても良きに解釈してくれる

msg = "this
       is
       a very
       long
       msg"

# heredoc
html = """
      <div id="main">
        hello
      </div>
       """
# =>
# var html;
# html = "<div id=\"main\">\n  hello\n</div>";

配列

配列を改行で扱える

a = [1,2,3];
b = [
  1
  3
  5 # インデントは揃える事
]

m = [0..5] => m = [0, 1, 2, 3, 4, 5];
n = [0...5] => n = [0, 1, 2, 3, 4];

console.log(m[1..3]) => [1,2]
console.log(m[1..-2]) => [1,2,3]
オブジェクト
m = {name: "woshidan", salary: 100};
m = name: "woshidan", salary: 100

m =
  name: "woshidan"
  salary: 100
m = {
  name: "woshidan",
  salary: {
    first: 100,
    second: 120
  }
}
m =
  name: "woshidan"
  salary:
    first: 100
    second: 120

if文ほか

  • == => === へ変換。is表記が使える
  • != => !=== へ変換。isnt表記が使える
  • true のエイリアスに yes / on
  • false のエイリアスに no / off
# block for if is presented by indent
if score > 60
  alert score

# if the command is a single line, i can use `then` key word to put command onto the line.
if score > 60 then alert score

# cannnot use condition ? a : b in coffee script
# when i want to write that expression, i can write as below.
msg = if score > 60 then "OK" else "NG"

10 < i < 20 => 10 < i && i < 20

要素が配列やオブジェクトの中にあるかどうか.

alert "OK" if 5 in [10, 9, 8]

# if (5 === 10 || 5 === 9 || 8 === 5) {
#   alert("OK");
# }

# オブジェクトの場合はof
alert "OK" if "score" of obj

# 配列の後ろに条件を付け加えられる

alert color for color in ["red", "blue", "pink"] when color isnt "blue"

# ref = ["red", "blue", "pink"];
# for (i = 0, len = ref.length; i < len; i++) {
#   color = ref[i];
#   if (color !== "blue") {
#     alert(color);
#   }
}

# item, i でindexも分かる(with_index的な)
for key, value of obj
  command

for item, index in array
  command

関数

# var greet = function () {} <= coffee script推薦
greet = function()
  alert "hi" # 字さげで

引数が無い時は()をつけて呼び出す。

引数のつけかたは矢印記号の前

greet = (name) -> alert "greet #{name}"
greet "woshidan"

引数に初期値を与える

greet = (name = "woshidan") -> alert "greet #{name}"
greet() #=> greet("woshidan")

即時関数

do -> alert "hello"

# (function() {
#   alert "hello";
# })();

分割代入

[a,b,c] = [1,5,10]

alert a alert b alert c

=> 1, 5, 10

[x, y] = [y, x]

関数の戻り値でも

results = (x) -> [x, x 2, x3] [a, b, c] = results 5

オブジェクトから一部の要素を取り出す

user = name: "woshidan" score: 0 email: "woshidan@example.com"

{name, email} = user alert name alert email

クラス

class User

var User;

User = (function() {
  function User() {}

  return User;

})();

# コンストラクターを書く
class User
  constructor: (name) ->
    this.name = name

# オブジェクトのthisは@で書ける
class User
  constructor: (name) ->
    @name = name # オブジェクトのthis => @

# コンストラクターで代入をするだけの場合は以下のように書ける
class User
  constructor: (@name) -> # 上と全く同じ意味だけど落ち着かない..!

継承はextend。 継承したクラスのコンストラクタを一部いじりたい場合は、 継承したクラスの生成コードの感じを覚えておくとよさそう。

AdminUser = (function(superClass) {
  extend(AdminUser, superClass);

  function AdminUser() {
    return AdminUser.__super__.constructor.apply(this, arguments);
  }

  return AdminUser;

})(User);

存在演算子

null / undefined の時だけ false を返す

rs = if x? then "found" else "not found"

var rs;

rs = typeof x !== "undefined" && x !== null ? "found" : "not found";

rubyのtry(存在しなければnilを返して後の処理をしない)っぽいことができる

user = 
  name: "woshidan"
# alert user.score.first => タイプエラー
# alert user.score?.first => undefined
# メソッドだった場合は関数かどうかも判定
alert user.sleep?()
# alert(typeof user.sleep === "function" ? user.sleep() : void 0);