ellios's blog

ellios's trivial story.

Coffeescript语法篇

| Comments

上一篇简单分析了下CoffeeScript的源码,这篇开始介绍CoffeeScript的语法。CoffeeScript的语法相比JavaScript要清爽好多,如果有Python,Ruby的经验的话,基本上半天就差不多了。CoffeeScript最终还是会被编译为JavaScript,所以基本的数据类型和JavaScript是一样,学习的时候和编译的JavaScript对应起来会更容易理解。

Examples

先睹为快,给个二分查找的例子。

二分查找例子 binary_search.coffee
1
2
3
4
5
6
7
8
9
10
11
12
index = (list, target) ->
  [low, high] = [0, list.length]
  while low < high
    mid = (low + high) >> 1
    val = list[mid]
    return mid if val is target
    if val < target then low = mid + 1 else high = mid
  return -1

console.log 2 is index [10, 20, 30, 40, 50], 30
console.log 4 is index [-97, 35, 67, 88, 1200], 1200
console.log 0 is index [0, 45, 70], 0

编译后的js代码如下

编译后的JS binary_search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
(function() {
  var index;

  index = function(list, target) {
    var high, low, mid, val, _ref;
    _ref = [0, list.length], low = _ref[0], high = _ref[1];
    while (low < high) {
      mid = (low + high) >> 1;
      val = list[mid];
      if (val === target) {
        return mid;
      }
      if (val < target) {
        low = mid + 1;
      } else {
        high = mid;
      }
    }
    return -1;
  };

  console.log(2 === index([10, 20, 30, 40, 50], 30));

  console.log(4 === index([-97, 35, 67, 88, 1200], 1200));

  console.log(0 === index([0, 45, 70], 0));

}).call(this);

后面会介绍CoffeeScript的各个语法点。

Functions

coffee函数
1
2
3
4
5
6
7
8
9
10
11
12
13
#匿名函数
console.log do -> "Hello World"
#非匿名函数,函数隐式返回最后一个表达式的值
square = (x) ->
  2 * x
  x * x
#调用函数
cube   = (x) -> square(x) * x
#函数可以有默认参数
fill = (container, liquid = "coffee") ->
  console.log "Filling the #{container} with #{liquid}..."
#函数绑定
setName = (name) -> @name = name;
编译后
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
(function() {
  var cube, fill, setName, square;

  console.log((function() {
    return "Hello World";
  })());

  square = function(x) {
    2 * x;
    return x * x;
  };

  cube = function(x) {
    return square(x) * x;
  };

  fill = function(container, liquid) {
    if (liquid == null) {
      liquid = "coffee";
    }
    return console.log("Filling the " + container + " with " + liquid + "...");
  };

  setName = function(name) {
    return this.name = name;
  };

}).call(this);

Comments