coffeeScript學習01

安裝

  • 這裏使用node.js
npm install -g coffee-script
# watch and compile
coffee -w --output lib --compile src
//
coffee -w -c index.coffee

語法

  • CoffeeScript不是JavaScript的超集,不能在CoffeeScript程序中寫JavaScript代碼

格式

  • CoffeeScript在編譯時爲每條語句加上;node

  • CoffeeScript中的註釋採用#npm

做用域

  • 會自動添加變量聲明‘var’,放到做用域的頂部

賦值

  • 字符串能夠用類ruby的語法內嵌
target = "world"
alert "hello, #{target}"    //注意雙引號
alert "hello" + target
  • 字面量
object1 = one: 1, two: 2
object2 =
  one: 1
  two: 2
arr1 = [1, 2]
arr2 = [
 1,
 2
]
  • 解構賦值
obj = {a:"foo", b:"bar"}
{a, b} = obj
arr = [1, 2]
[a, b] = arr

數組

  • 數組的操做引入了來自ruby的Range概念,而且能夠將字符串徹底做爲數組操做
numbers = [0..9]  //兩個或三個點號
numbers[3..5] = [-3,-4,-5]   //替換number 3-5的值;能夠是任意個數
my = "my string"[0..1]
  • 判斷一個值是否在數組內
arr = ["foo", "bar"]
"foo" in arr
  • for..in語法
for name, i in ["roger", "roderick"]
  alert "#{i} - Release #{name}"
  • 過濾器when
items = ["ranger", "roderick", "brian"]
alert 'ok' for item in items when item is "ranger"
  • 能夠用()收集遍歷的結果
items = [{id: 0, name: "ranger"}, {id: 1, name: "roderick"}, {id: 2, name: "brian"}]
result = (item for item in items when item.id is 1)   //注意前面有個item;以數組形式返回

流程控制

函數

  • CoffeeScript對JavaScript的函數作了很大的簡化
sum = (nums) ->
  nums.reduce(x, y) -> x + y

sum 1,2,3

//
(function() {
  var sum;

  sum = function(nums) {
    return nums.reduce(x, y)(function() {
      return x + y;
    });
  };

  sum(1, 2, 3);

}).call(this);
  • ->來代替function; 注意前面空一格
  • 參數列表放在->的前邊,且可省略
  • 取消了函數聲明,只能將函數做爲值定義
  • 在CoffeeScript中,任何語句都是表達式(除了break和continue),都有返回值,所以像ruby同樣,不須要顯式return
  • CoffeeScript的函數能夠有默認參數
times = (a = 1, b = 2) -> a * b
  • CoffeeScript的函數調用能夠不用()語法包圍參數,像ruby同樣跟在函數名後面就能夠,不過這也有時候會帶來問題,特別是沒有參數的調用數組

  • 縮進的格式有時須要當心,好比用多個函數作參數的時候ruby

$(".toggle").toggle ->
  "on"
, ->
  "off"

//
(function() {
  $(".toggle").toggle(function() {
    return "on";
  }, function() {
    return "off";
  });

}).call(this);
相關文章
相關標籤/搜索