CoffeeScript

为什么80%的码农都做不了架构师?>>>   hot3.png

CoffeeScript 是一门编译到 JavaScript 的小巧语言. 在 Java 般笨拙的外表下, JavaScript 其实有着一颗华丽的心脏. CoffeeScript 尝试用简洁的方式展示 JavaScript 优秀的部分.

CoffeeScript 的指导原则是: "她仅仅是 JavaScript". 代码一一对应地编译到 JS, 不会在编译过程中进行解释. 已有的 JavaScript 类库可以无缝地和 CoffeeScript 搭配使用, 反之亦然. 编译后的代码是可读的, 且经过美化, 能在所有 JavaScript 环境中运行, 并且应该和对应手写的 JavaScript 一样快或者更快.

最新版本: 1.7.1

sudo npm install -g coffee-script

概览

左边是 CoffeeScript, 右边是编译后输出的 JavaScript.

# 赋值:number   = 42opposite = true# 条件:number = -42 if opposite# 函数:square = (x) -> x * x# 数组:list = [1, 2, 3, 4, 5]# 对象:math =  root:   Math.sqrt  square: square  cube:   (x) -> x * square x# Splats:race = (winner, runners...) ->
  print winner, runners# 存在性:alert "I knew it!" if elvis?# 数组 推导(comprehensions):cubes = (math.cube num for num in list)

var cubes, list, math, num, number, opposite, race, square,
  __slice = [].slice;

number = 42;

opposite = true;if (opposite) {
  number = -42;
}

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

list = [1, 2, 3, 4, 5];

math = {
  root: Math.sqrt,
  square: square,
  cube: function(x) {
    return x * square(x);
  }
};

race = function() {
  var runners, winner;
  winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : [];  return print(winner, runners);
};if (typeof elvis !== "undefined" && elvis !== null) {
  alert("I knew it!");
}

cubes = (function() {
  var _i, _len, _results;
  _results = [];  for (_i = 0, _len = list.length; _i < _len; _i++) {
    num = list[_i];
    _results.push(math.cube(num));
  }  return _results;
})();

run: cubes


安装

CoffeeScript 编译器本身是 CoffeeScript 写的, 使用了 Jison parser generator. 命令行版本的 coffee 是一个实用的 Node.js 工具. 不过编译器并不依赖 Node, 而是能运行于任何 JavaScript 执行环境, 比如说在浏览器里(看上边的"试一试 CoffeeScript").

安装前你需要最新稳定版 Node.js, 和 npm (Node Package Manager). 借助 npm 可以安装 CoffeeScript:

npm install -g coffee-script

(如果不想全局安装可以去掉 -g 选项.)

如果你希望安装 master 分支上最新的 CoffeeScript, 你可以从源码仓库 克隆 CoffeeScript, 或直接下载源码. 还有通过 npm 方式安装 master 分支最新的 CoffeeScript 编译器:

npm install -g http://github.com/jashkenas/coffee-script/tarball/master

或者你想将其安装到 /usr/local, 而不用 npm 进行管理, 进入 coffee-script 目录执行:

sudo bin/cake install

用法

安装之后, 你应该可以运行 coffee 命令以执行脚本, 编译 .coffee 文件到 .js 文件, 和提供一个交互式的 REPL. coffee 命令有下列参数:

-c, --compile 编译一个 .coffee 脚本到一个同名的 .js 文件.
-m, --map 随 JavaScript 文件一起生成 source maps. 并且在 JavaScript 里加上 sourceMappingURL 指令.
-i, --interactive 启动一个交互式的 CoffeeScript 会话用来尝试一些代码片段. 等同于执行 coffee 而不加参数.
-o, --output [DIR] 将所有编译后的 JavaScript 文件写到指定文件夹. 与 --compile 或 --watch 搭配使用.
-j, --join [FILE] 编译之前, 按参数传入顺序连接所有脚本到一起, 编译后写到指定的文件. 对于编译大型项目有用.
-w, --watch 监视文件改变, 任何文件更新时重新执行命令.
-p, --print JavaScript 直接打印到 stdout 而不是写到一个文件.
-s, --stdio 将 CoffeeScript 传递到 STDIN 后从 STDOUT 获取 JavaScript. 对其他语言写的进程有好处. 比如:
cat src/cake.coffee | coffee -sc
-l, --literate 将代码作为 Literate CoffeeScript 解析. 只会在从 stdio 直接传入代码或者处理某些没有后缀的文件名需要写明这点.
-e, --eval 直接从命令行编译和打印一小段 CoffeeScript. 比如:
coffee -e "console.log num for num in [10..1]"
-b, --bare 编译到 JavaScript 时去掉顶层函数的包裹.
-t, --tokens 不对 CoffeeScript 进行解析, 仅仅进行 lex, 打印出 token stream: [IDENTIFIER square] [ASSIGN =] [PARAM_START (] ...
-n, --nodes 不对 CoffeeScript 进行编译, 仅仅 lex 和解析, 打印 parse tree:
Expressions
  Assign
    Value "square"
    Code "x"
      Op *
        Value "x"
        Value "x"
--nodejs node 命令有一些实用的参数, 比如
--debug, --debug-brk, --max-stack-size, 和 --expose-gc. 用这个参数直接把参数转发到 Node.js. 重复使用 --nodejs 来传递多个参数.

例子:

  • 编译一个 .coffee 文件的树形目录 src 到一个同级 .js 文件树形目录 lib:
    coffee --compile --output lib/ src/

  • 监视一个文件的改变, 每次文件被保证时重新编译:
    coffee --watch --compile experimental.coffee

  • 合并一组文件到单个脚本:
    coffee --join project.js --compile src/*.coffee

  • 从一个 one-liner 打印编译后的 JS:
    coffee -bpe "alert i for i in [0..10]"

  • 现在全部一起, 在你工作时监视和重复编译整个项目:
    coffee -o lib/ -cw src/

  • 运行 CoffeeScript REPL (Ctrl-D 来终止, Ctrl-V 激活多行):
    coffee

Literate CoffeeScript

除了被作为一个普通的编程语言, CoffeeScript 也可以在 "literate" 模式下编写。 如果你以 .litcoffee 为扩展名命名你的文件, 你可以把它当作 Markdown 文件来编写 — 此文档恰好也是一份可执行的 CoffeeScript 代码, 编译器将会把所有的缩进块 (Markdown 表示源代码的方式) 视为代码, 其他部分则为注释.

Just for kicks, a little bit of the compiler is currently implemented in this fashion: See it as a document, raw, and properly highlighted in a text editor.

I'm fairly excited about this direction for the language, and am looking forward to writing (and more importantly, reading) more programs in this style. More information about Literate CoffeeScript, including an example program, are available in this blog post.

语言手册

这份手册所设计的结构, 方便从上往下进行阅读. 后边的章节使用前面介绍的语法和手法. 阅读这份手册需要对 JavaScript 比较熟悉. 以下所有的例子, CoffeeScript 源码将在左边显示, 并在右侧直接编译到 JavaScript.

很多例子可以通过点击右边的 run 按钮直接运行(代码有意义的话), 也可以通过点击左边的 load 按钮载入"试一试 CoffeeScript"的控制台.

首先, 一些基础, CoffeeScript 使用显式的空白来区分代码块. 你不需要使用分号 ; 来关闭表达式, 在一行的结尾换行就可以了(尽管分号依然可以用来把多行的表达式简写到一行里). 不需要再用花括号来 { } 包裹代码快, 在 函数, if 表达式, switch, 和 try/catch 当中使用缩进.

传入参数的时候, 你不需要再使用圆括号来表明函数被执行. 隐式的函数调用的作用范围一直到行尾或者一个块级表达式.
console.log sys.inspect object → console.log(sys.inspect(object));

函数 函数通过一组可选的圆括号包裹的参数, 一个箭头, 一个函数体来定义. 一个空的函数像是这样: ->

square = (x) -> x * xcube   = (x) -> square(x) * x

var cube, square;

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

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

load

run: cube(5)


一些函数函数参数会有默认值, 当传入的参数的不存在 (null 或者 undefined) 时会被使用.

fill = (container, liquid = "coffee") ->
  "Filling the #{container} with #{liquid}..."

var fill;

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

load

run: fill("cup")


对象和数组 CoffeeScript 中对象和数组的字面量看起来很像在 JavaScript 中的写法. 如果单个属性被写在自己的一行里, 那么逗号是可以省略的. 和 YAML 类似, 对象可以用缩进替代花括号来声明.

song = ["do", "re", "mi", "fa", "so"]

singers = {Jagger: "Rock", Elvis: "Roll"}

bitlist = [  1, 0, 1
  0, 0, 1
  1, 1, 0]

kids =  brother:    name: "Max"
    age:  11
  sister:    name: "Ida"
    age:  9

var bitlist, kids, singers, song;

song = ["do", "re", "mi", "fa", "so"];

singers = {
  Jagger: "Rock",
  Elvis: "Roll"};

bitlist = [1, 0, 1, 0, 0, 1, 1, 1, 0];

kids = {
  brother: {
    name: "Max",
    age: 11
  },
  sister: {
    name: "Ida",
    age: 9
  }
};

load

run: song.join(" ... ")


JavaScript 里, 你不能使用不添加引号的保留字段作为属性名称, 比如 class. CoffeeScript 里作为键出现的保留字会被识别并补上引号, 所以你不用有额外的操心(比如说, 使用 jQuery 的时候).

$('.account').attr class: 'active'

log object.class

$('.account').attr({  "class": 'active'});

log(object["class"]);

load


词法作用域和变量安全 CoffeeScript 编译器会考虑所有变量, 保证每个变量都在词法域里适当地被定义 — 你永远不需要自己去写 var.

outer = 1changeNumbers = ->
  inner = -1
  outer = 10inner = changeNumbers()

var changeNumbers, inner, outer;

outer = 1;

changeNumbers = function() {
  var inner;
  inner = -1;  return outer = 10;
};

inner = changeNumbers();

load

run: inner


注意所有变量的定义都被推到相关的顶层作用域, 也就是第一次出现的位置. outer 在内层的函数里没有被重新定义, 因为它已经存在于作用域当中了. 同时, 内层函数里的 inner 不应该改变外部的同名的变量, 所以在这里有自己的声明.

其行为和 Ruby 的局部变量的作用域实际上是一致的. 由于你没有对 var 关键字的直接访问, 根据需要隐藏一个外部变量就很容易, 你只能引用它. 所以在写深层的嵌套的函数时, 注意不要意外用到和外部变量相同的名字.

尽管要说清楚会受到文档长度限制, 函数的所有 CoffeeScript 结果都被一个匿名函数包裹: (function(){ ... })(); 这层安全的封装, 加上自动生成的 var 关键字, 使得不小心污染全局命名空间很难发生.

如果你希望创建一个其他脚本也能使用的顶层变量, 那么将其作为赋值在 window 上, 或者在 CommonJS 里的 exports 上. 存在操作符(existential operator)可以帮你写出一个可靠的方式找到添加位置; 比如你的目标是同时满足 CommonJS 和浏览器: exports ? this

if, else, unless 和条件赋值 if/else 表达式可以不用圆括号和花括号就写出来. 就像函数和其他块级表达式那样, 多行的条件可以通过缩进来表明. 另外还有一个顺手的后缀形式, 在行尾使用 if or unless.

CoffeeScript 会尝试编译 if 语句到 JavaScript 表达式, 或者一个封装的闭包. CoffeeScript 里不存在直白的三元表达式. — 你只要在一行内使用普通的 if 语句.

mood = greatlyImproved if singingif happy and knowsIt
  clapsHands()
  chaChaCha()else
  showIt()

date = if friday then sue else jill

var date, mood;if (singing) {
  mood = greatlyImproved;
}if (happy && knowsIt) {
  clapsHands();
  chaChaCha();
} else {
  showIt();
}

date = friday ? sue : jill;

load


变参(splats)... 使用 JavaScript 的 arguments 对象是一种处理接收不定数量个参数的函数常用办法. CoffeeScript 在函数定义和调用里提供了变参(splats) ... 的语法, 让不定个数的参数使用起来更愉悦一些.

gold = silver = rest = "unknown"awardMedals = (first, second, others...) ->
  gold   = first
  silver = second
  rest   = others

contenders = [  "Michael Phelps"
  "Liu Xiang"
  "Yao Ming"
  "Allyson Felix"
  "Shawn Johnson"
  "Roman Sebrle"
  "Guo Jingjing"
  "Tyson Gay"
  "Asafa Powell"
  "Usain Bolt"]

awardMedals contenders...

alert "Gold: " + gold
alert "Silver: " + silver
alert "The Field: " + rest

var awardMedals, contenders, gold, rest, silver,
  __slice = [].slice;

gold = silver = rest = "unknown";

awardMedals = function() {
  var first, others, second;
  first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
  gold = first;
  silver = second;  return rest = others;
};

contenders = ["Michael Phelps", "Liu Xiang", "Yao Ming", "Allyson Felix", "Shawn Johnson", "Roman Sebrle", "Guo Jingjing", "Tyson Gay", "Asafa Powell", "Usain Bolt"];

awardMedals.apply(null, contenders);

alert("Gold: " + gold);

alert("Silver: " + silver);

alert("The Field: " + rest);

load

run


Loops and Comprehensions Most of the loops you'll write in CoffeeScript will be comprehensions over arrays, objects, and ranges. Comprehensions replace (and compile into) for loops, with optional guard clauses and the value of the current array index. Unlike for loops, array comprehensions are expressions, and can be returned and assigned.

# 吃午饭.eat food for food in ['toast', 'cheese', 'wine']# 精致的五道菜.courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu i + 1, dish for dish, i in courses# 注重健康的一餐.foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate'

var courses, dish, food, foods, i, _i, _j, _k, _len, _len1, _len2, _ref;

_ref = ['toast', 'cheese', 'wine'];for (_i = 0, _len = _ref.length; _i < _len; _i++) {
  food = _ref[_i];
  eat(food);
}

courses = ['greens', 'caviar', 'truffles', 'roast', 'cake'];for (i = _j = 0, _len1 = courses.length; _j < _len1; i = ++_j) {
  dish = courses[i];
  menu(i + 1, dish);
}

foods = ['broccoli', 'spinach', 'chocolate'];for (_k = 0, _len2 = foods.length; _k < _len2; _k++) {
  food = foods[_k];  if (food !== 'chocolate') {
    eat(food);
  }
}

load


Comprehensions should be able to handle most places where you otherwise would use a loop, each/forEach, map, or select/filter, for example: shortNames = (name for name in list when name.length < 5)
If you know the start and end of your loop, or would like to step through in fixed-size increments, you can use a range to specify the start and end of your comprehension.

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

var countdown, num;

countdown = (function() {
  var _i, _results;
  _results = [];  for (num = _i = 10; _i >= 1; num = --_i) {
    _results.push(num);
  }  return _results;
})();

load

run: countdown


Note how because we are assigning the value of the comprehensions to a variable in the example above, CoffeeScript is collecting the result of each iteration into an array. Sometimes functions end with loops that are intended to run only for their side-effects. Be careful that you're not accidentally returning the results of the comprehension in these cases, by adding a meaningful return value — like true — or null, to the bottom of your function.

To step through a range comprehension in fixed-size chunks, use by, for example:
evens = (x for x in [0..10] by 2)

Comprehensions can also be used to iterate over the keys and values in an object. Use of to signal comprehension over the properties of an object instead of the values in an array.

yearsOld = max: 10, ida: 9, tim: 11ages = for child, age of yearsOld  "#{child} is #{age}"

var age, ages, child, yearsOld;

yearsOld = {
  max: 10,
  ida: 9,
  tim: 11};

ages = (function() {
  var _results;
  _results = [];  for (child in yearsOld) {
    age = yearsOld[child];
    _results.push("" + child + " is " + age);
  }  return _results;
})();

load

run: ages.join(", ")


If you would like to iterate over just the keys that are defined on the object itself, by adding a hasOwnProperty check to avoid properties that may be inherited from the prototype, use
for own key, value of object

The only low-level loop that CoffeeScript provides is the while loop. The main difference from JavaScript is that the while loop can be used as an expression, returning an array containing the result of each iteration through the loop.

# 经济 101if this.studyingEconomics
  buy()  while supply > demand
  sell() until supply > demand# 摇篮曲num = 6lyrics = while num -= 1
  "#{num} little monkeys, jumping on the bed.
    One fell out and bumped his head."

var lyrics, num;if (this.studyingEconomics) {  while (supply > demand) {
    buy();
  }  while (!(supply > demand)) {
    sell();
  }
}

num = 6;

lyrics = (function() {
  var _results;
  _results = [];  while (num -= 1) {
    _results.push("" + num + " little monkeys, jumping on the bed. One fell out and bumped his head.");
  }  return _results;
})();

load

run: lyrics.join(" ")


For readability, the until keyword is equivalent to while not, and the loop keyword is equivalent to while true.

When using a JavaScript loop to generate functions, it's common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don't just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.

for filename in list  do (filename) ->
    fs.readFile filename, (err, contents) ->
      compile filename, contents.toString()

var filename, _fn, _i, _len;

_fn = function(filename) {
  return fs.readFile(filename, function(err, contents) {
    return compile(filename, contents.toString());
  });
};for (_i = 0, _len = list.length; _i < _len; _i++) {
  filename = list[_i];
  _fn(filename);
}

load


Array Slicing and Splicing with Ranges Ranges can also be used to extract slices of arrays. With two dots (3..6), the range is inclusive (3, 4, 5, 6); with three dots (3...6), the range excludes the end (3, 4, 5). Slices indices have useful defaults. An omitted first index defaults to zero and an omitted second index defaults to the size of the array.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]

start   = numbers[0..2]

middle  = numbers[3...-2]

end     = numbers[-2..]

copy    = numbers[..]

var copy, end, middle, numbers, start;

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

start = numbers.slice(0, 3);

middle = numbers.slice(3, -2);

end = numbers.slice(-2);

copy = numbers.slice(0);

load

run: middle


The same syntax can be used with assignment to replace a segment of an array with new values, splicing it.

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

numbers[3..6] = [-3, -4, -5, -6]

var numbers, _ref;

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

[].splice.apply(numbers, [3, 4].concat(_ref = [-3, -4, -5, -6])), _ref;

load

run: numbers


Note that JavaScript strings are immutable, and can't be spliced.

Everything is an Expression (at least, as much as possible) You might have noticed how even though we don't add return statements to CoffeeScript functions, they nonetheless return their final value. The CoffeeScript compiler tries to make sure that all statements in the language can be used as expressions. Watch how the return gets pushed down into each possible branch of execution in the function below.

grade = (student) ->
  if student.excellentWork    "A+"
  else if student.okayStuff    if student.triedHard then "B" else "B-"
  else
    "C"eldest = if 24 > 21 then "Liz" else "Ike"

var eldest, grade;

grade = function(student) {
  if (student.excellentWork) {    return "A+";
  } else if (student.okayStuff) {    if (student.triedHard) {      return "B";
    } else {      return "B-";
    }
  } else {    return "C";
  }
};

eldest = 24 > 21 ? "Liz" : "Ike";

load

run: eldest


Even though functions will always return their final value, it's both possible and encouraged to return early from a function body writing out the explicit return (return value), when you know that you're done.

Because variable declarations occur at the top of scope, assignment can be used within expressions, even for variables that haven't been seen before:

six = (one = 1) + (two = 2) + (three = 3)

var one, six, three, two;

six = (one = 1) + (two = 2) + (three = 3);

load

run: six


Things that would otherwise be statements in JavaScript, when used as part of an expression in CoffeeScript, are converted into expressions by wrapping them in a closure. This lets you do useful things, like assign the result of a comprehension to a variable:

# 前十个全局属性(变量).globals = (name for name of window)[0...10]

var globals, name;

globals = ((function() {
  var _results;
  _results = [];  for (name in window) {
    _results.push(name);
  }  return _results;
})()).slice(0, 10);

load

run: globals


As well as silly things, like passing a try/catch statement directly into a function call:

alert(  try
    nonexistent / undefined
  catch error    "And the error is ... #{error}")

var error;

alert((function() {
  try {    return nonexistent / void 0;
  } catch (_error) {
    error = _error;    return "And the error is ... " + error;
  }
})());

load

run


There are a handful of statements in JavaScript that can't be meaningfully converted into expressions, namely break, continue, and return. If you make use of them within a block of code, CoffeeScript won't try to perform the conversion.

Operators and Aliases Because the == operator frequently causes undesirable coercion, is intransitive, and has a different meaning than in other languages, CoffeeScript compiles == into ===, and != into !==. In addition, is compiles into ===, and isnt into !==.

You can use not as an alias for !.

For logic, and compiles to &&, and or into ||.

Instead of a newline or semicolon, then can be used to separate conditions from expressions, in while, if/else, and switch/when statements.

As in YAML, on and yes are the same as boolean true, while off and no are boolean false.

unless can be used as the inverse of if.

As a shortcut for this.property, you can use @property.

You can use in to test for array presence, and of to test for JavaScript object-key presence.

To simplify math expressions, ** can be used for exponentiation, // performs integer division and %% provides true mathematical modulo.

All together now:

CoffeeScript JavaScript
is ===
isnt !==
not !
and &&
or ||
true, yes, on true
false, no, off false
@, this this
of in
in no JS equivalent
a ** b Math.pow(a, b)
a // b Math.floor(a / b)
a %% b (a % b + b) % b
launch() if ignition is onvolume = 10 if band isnt SpinalTap

letTheWildRumpusBegin() unless answer is noif car.speed < limit then accelerate()

winner = yes if pick in [47, 92, 13]print inspect "My name is #{@name}"

var volume, winner;if (ignition === true) {
  launch();
}if (band !== SpinalTap) {
  volume = 10;
}if (answer !== false) {
  letTheWildRumpusBegin();
}if (car.speed < limit) {
  accelerate();
}if (pick === 47 || pick === 92 || pick === 13) {
  winner = true;
}

print(inspect("My name is " + this.name));

load


The Existential Operator It's a little difficult to check for the existence of a variable in JavaScript. if (variable) ... comes close, but fails for zero, the empty string, and false. CoffeeScript's existential operator ? returns true unless a variable is null or undefined, which makes it analogous to Ruby's nil?

It can also be used for safer conditional assignment than ||= provides, for cases where you may be handling numbers or strings.

solipsism = true if mind? and not world?

speed = 0speed ?= 15footprints = yeti ? "bear"

var footprints, solipsism, speed;if ((typeof mind !== "undefined" && mind !== null) && (typeof world === "undefined" || world === null)) {
  solipsism = true;
}

speed = 0;if (speed == null) {
  speed = 15;
}

footprints = typeof yeti !== "undefined" && yeti !== null ? yeti : "bear";

load

run: footprints


The accessor variant of the existential operator ?. can be used to soak up null references in a chain of properties. Use it instead of the dot accessor . in cases where the base value may be null or undefined. If all of the properties exist then you'll get the expected result, if the chain is broken, undefined is returned instead of the TypeError that would be raised otherwise.

zip = lottery.drawWinner?().address?.zipcode

var zip, _ref;

zip = typeof lottery.drawWinner === "function" ? (_ref = lottery.drawWinner().address) != null ? _ref.zipcode : void 0 : void 0;

load


Soaking up nulls is similar to Ruby's andand gem, and to the safe navigation operator in Groovy.

Classes, Inheritance, and Super JavaScript's prototypal inheritance has always been a bit of a brain-bender, with a whole family tree of libraries that provide a cleaner syntax for classical inheritance on top of JavaScript's prototypes: Base2, Prototype.js, JS.Class, etc. The libraries provide syntactic sugar, but the built-in inheritance would be completely usable if it weren't for a couple of small exceptions: it's awkward to call super (the prototype object's implementation of the current function), and it's awkward to correctly set the prototype chain.

Instead of repetitively attaching functions to a prototype, CoffeeScript provides a basic class structure that allows you to name your class, set the superclass, assign prototypal properties, and define the constructor, in a single assignable expression.

Constructor functions are named, to better support helpful stack traces. In the first class in the example below, this.constructor.name is "Animal".

class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45sam = new Snake "Sammy the Python"tom = new Horse "Tommy the Palomino"sam.move()
tom.move()

var Animal, Horse, Snake, sam, tom,
  __hasProp = {}.hasOwnProperty,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };

Animal = (function() {
  function Animal(name) {
    this.name = name;
  }

  Animal.prototype.move = function(meters) {
    return alert(this.name + (" moved " + meters + "m."));
  };  return Animal;

})();

Snake = (function(_super) {
  __extends(Snake, _super);  function Snake() {
    return Snake.__super__.constructor.apply(this, arguments);
  }

  Snake.prototype.move = function() {
    alert("Slithering...");    return Snake.__super__.move.call(this, 5);
  };  return Snake;

})(Animal);

Horse = (function(_super) {
  __extends(Horse, _super);  function Horse() {
    return Horse.__super__.constructor.apply(this, arguments);
  }

  Horse.prototype.move = function() {
    alert("Galloping...");    return Horse.__super__.move.call(this, 45);
  };  return Horse;

})(Animal);

sam = new Snake("Sammy the Python");

tom = new Horse("Tommy the Palomino");

sam.move();

tom.move();

load

run


If structuring your prototypes classically isn't your cup of tea, CoffeeScript provides a couple of lower-level conveniences. The extends operator helps with proper prototype setup, and can be used to create an inheritance chain between any pair of constructor functions; :: gives you quick access to an object's prototype; and super() is converted into a call against the immediate ancestor's method of the same name.

String::dasherize = ->
  this.replace /_/g, "-"

String.prototype.dasherize = function() {
  return this.replace(/_/g, "-");
};

load

run: "one_two".dasherize()


Finally, class definitions are blocks of executable code, which make for interesting metaprogramming possibilities. Because in the context of a class definition, this is the class object itself (the constructor function), you can assign static properties by using
@property: value, and call functions defined in parent classes: @attr 'title', type: 'text'

Destructuring Assignment To make extracting values from complex arrays and objects more convenient, CoffeeScript implements ECMAScript Harmony's proposed destructuring assignment syntax. When you assign an array or object literal to a value, CoffeeScript breaks up and matches both sides against each other, assigning the values on the right to the variables on the left. In the simplest case, it can be used for parallel assignment:

theBait   = 1000theSwitch = 0[theBait, theSwitch] = [theSwitch, theBait]

var theBait, theSwitch, _ref;

theBait = 1000;

theSwitch = 0;

_ref = [theSwitch, theBait], theBait = _ref[0], theSwitch = _ref[1];

load

run: theBait


But it's also helpful for dealing with functions that return multiple values.

weatherReport = (location) ->
  # 发起一个 Ajax 请求获取天气...
  [location, 72, "Mostly Sunny"]

[city, temp, forecast] = weatherReport "Berkeley, CA"

var city, forecast, temp, weatherReport, _ref;

weatherReport = function(location) {
  return [location, 72, "Mostly Sunny"];
};

_ref = weatherReport("Berkeley, CA"), city = _ref[0], temp = _ref[1], forecast = _ref[2];

load

run: forecast


Destructuring assignment can be used with any depth of array and object nesting, to help pull out deeply nested properties.

futurists =  sculptor: "Umberto Boccioni"
  painter:  "Vladimir Burliuk"
  poet:    name:   "F.T. Marinetti"
    address: [      "Via Roma 42R"
      "Bellagio, Italy 22021"
    ]

{poet: {name, address: [street, city]}} = futurists

var city, futurists, name, street, _ref, _ref1;

futurists = {
  sculptor: "Umberto Boccioni",
  painter: "Vladimir Burliuk",
  poet: {
    name: "F.T. Marinetti",
    address: ["Via Roma 42R", "Bellagio, Italy 22021"]
  }
};

_ref = futurists.poet, name = _ref.name, (_ref1 = _ref.address, street = _ref1[0], city = _ref1[1]);

load

run: "name + "-" + street"


Destructuring assignment can even be combined with splats.

tag = ""[open, contents..., close] = tag.split("")

var close, contents, open, tag, _i, _ref,
  __slice = [].slice;

tag = "";

_ref = tag.split(""), open = _ref[0], contents = 3 <= _ref.length ? __slice.call(_ref, 1, _i = _ref.length - 1) : (_i = 1, []), close = _ref[_i++];

load

run: contents.join("")


Expansion can be used to retrieve elements from the end of an array without having to assign the rest of its values. It works in function parameter lists as well.

text = "Every literary critic believes he will
        outwit history and have the last word"[first, ..., last] = text.split " "

var first, last, text, _ref;

text = "Every literary critic believes he will outwit history and have the last word";

_ref = text.split(" "), first = _ref[0], last = _ref[_ref.length - 1];

load

run: "first + " " + last"


Destructuring assignment is also useful when combined with class constructors to assign properties to your instance from an options object passed to the constructor.

class Person
  constructor: (options) -> 
    {@name, @age, @height} = options

tim = new Person age: 4

var Person, tim;

Person = (function() {
  function Person(options) {
    this.name = options.name, this.age = options.age, this.height = options.height;
  }  return Person;

})();

tim = new Person({
  age: 4});

load

run: tim.age


Function binding In JavaScript, the this keyword is dynamically scoped to mean the object that the current function is attached to. If you pass a function as a callback or attach it to a different object, the original value of this will be lost. If you're not familiar with this behavior, this Digital Web article gives a good overview of the quirks.

The fat arrow => can be used to both define a function, and to bind it to the current value of this, right on the spot. This is helpful when using callback-based libraries like Prototype or jQuery, for creating iterator functions to pass to each, or event-handler functions to use with bind. Functions created with the fat arrow are able to access properties of the this where they're defined.

Account = (customer, cart) ->
  @customer = customer  @cart = cart

  $('.shopping_cart').bind 'click', (event) =>
    @customer.purchase @cart

var Account;

Account = function(customer, cart) {
  this.customer = customer;  this.cart = cart;  return $('.shopping_cart').bind('click', (function(_this) {
    return function(event) {
      return _this.customer.purchase(_this.cart);
    };
  })(this));
};

load


If we had used -> in the callback above, @customer would have referred to the undefined "customer" property of the DOM element, and trying to call purchase() on it would have raised an exception.

When used in a class definition, methods declared with the fat arrow will be automatically bound to each instance of the class when the instance is constructed.

Embedded JavaScript Hopefully, you'll never need to use it, but if you ever need to intersperse snippets of JavaScript within your CoffeeScript, you can use backticks to pass it straight through.

hi = `function() {
  return [document.title, "Hello JavaScript"].join(": ");
}`

var hi;

hi = function() {
  return [document.title, "Hello JavaScript"].join(": ");
};

load

run: hi()


Switch/When/Else Switch statements in JavaScript are a bit awkward. You need to remember to break at the end of every case statement to avoid accidentally falling through to the default case. CoffeeScript prevents accidental fall-through, and can convert the switch into a returnable, assignable expression. The format is: switch condition, when clauses, else the default case.

As in Ruby, switch statements in CoffeeScript can take multiple values for each when clause. If any of the values match, the clause runs.

switch day  when "Mon" then go work  when "Tue" then go relax  when "Thu" then go iceFishing  when "Fri", "Sat"
    if day is bingoDay
      go bingo
      go dancing  when "Sun" then go church  else go work

switch (day) {  case "Mon":
    go(work);    break;  case "Tue":
    go(relax);    break;  case "Thu":
    go(iceFishing);    break;  case "Fri":  case "Sat":    if (day === bingoDay) {
      go(bingo);
      go(dancing);
    }    break;  case "Sun":
    go(church);    break;  default:
    go(work);
}

load


Switch statements can also be used without a control expression, turning them in to a cleaner alternative to if/else chains.

score = 76grade = switch
  when score < 60 then 'F'
  when score < 70 then 'D'
  when score < 80 then 'C'
  when score < 90 then 'B'
  else 'A'# grade == 'C'

var grade, score;

score = 76;

grade = (function() {
  switch (false) {    case !(score < 60):      return 'F';    case !(score < 70):      return 'D';    case !(score < 80):      return 'C';    case !(score < 90):      return 'B';    default:      return 'A';
  }
})();

load


Try/Catch/Finally Try/catch statements are just about the same as JavaScript (although they work as expressions).

try
  allHellBreaksLoose()
  catsAndDogsLivingTogether()catch error  print errorfinally
  cleanUp()

var error;try {
  allHellBreaksLoose();
  catsAndDogsLivingTogether();
} catch (_error) {
  error = _error;
  print(error);
} finally {
  cleanUp();
}

load


Chained Comparisons CoffeeScript borrows chained comparisons from Python — making it easy to test if a value falls within a certain range.

cholesterol = 127healthy = 200 > cholesterol > 60

var cholesterol, healthy;

cholesterol = 127;

healthy = (200 > cholesterol && cholesterol > 60);

load

run: healthy


String Interpolation, Block Strings, and Block Comments Ruby-style string interpolation is included in CoffeeScript. Double-quoted strings allow for interpolated values, using #{ ... }, and single-quoted strings are literal.

author = "Wittgenstein"quote  = "A picture is a fact. -- #{ author }"sentence = "#{ 22 / 7 } is a decent approximation of π"

var author, quote, sentence;

author = "Wittgenstein";

quote = "A picture is a fact. -- " + author;

sentence = "" + (22 / 7) + " is a decent approximation of π";

load

run: sentence


Multiline strings are allowed in CoffeeScript. Lines are joined by a single space unless they end with a backslash. Indentation is ignored.

mobyDick = "Call me Ishmael. Some years ago --
  never mind how long precisely -- having little
  or no money in my purse, and nothing particular
  to interest me on shore, I thought I would sail
  about a little and see the watery part of the
  world..."

var mobyDick;

mobyDick = "Call me Ishmael. Some years ago -- never mind how long precisely -- having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world...";

load

run: mobyDick


Block strings can be used to hold formatted or indentation-sensitive text (or, if you just don't feel like escaping quotes and apostrophes). The indentation level that begins the block is maintained throughout, so you can keep it all aligned with the body of your code.

html = """
       
         cup of coffeescript
       
       """

var html;

html = "\n  cup of coffeescript\n";

load

run: html


Double-quoted block strings, like other double-quoted strings, allow interpolation.

Sometimes you'd like to pass a block comment through to the generated JavaScript. For example, when you need to embed a licensing header at the top of a file. Block comments, which mirror the syntax for block strings, are preserved in the generated code.

###
SkinnyMochaHalfCaffScript Compiler v1.0
Released under the MIT License
###

/*
SkinnyMochaHalfCaffScript Compiler v1.0
Released under the MIT License
 */

load


Block Regular Expressions Similar to block strings and comments, CoffeeScript supports block regexes — extended regular expressions that ignore internal whitespace and can contain comments and interpolation. Modeled after Perl's /x modifier, CoffeeScript's block regexes are delimited by /// and go a long way towards making complex regular expressions readable. To quote from the CoffeeScript source:

OPERATOR = /// ^ (
  ?: [-=]>             # 函数
   | [-+*/%<>&|^!?=]=  # 复合赋值 / 比较
   | >>>=?             # 补 0 右移
   | ([-+:])\1         # 双写
   | ([&|<>])\2=?      # 逻辑 / 移位
   | \?\.              # soak 访问
   | \.{2,3}           # 范围或者 splat) ///

var OPERATOR;

OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/;

load


Cake, and Cakefiles

CoffeeScript includes a (very) simple build system similar to Make and Rake. Naturally, it's called Cake, and is used for the tasks that build and test the CoffeeScript language itself. Tasks are defined in a file named Cakefile, and can be invoked by running cake [task] from within the directory. To print a list of all the tasks and options, just type cake.

Task definitions are written in CoffeeScript, so you can put arbitrary code in your Cakefile. Define a task with a name, a long description, and the function to invoke when the task is run. If your task takes a command-line option, you can define the option with short and long flags, and it will be made available in the options object. Here's a task that uses the Node.js API to rebuild CoffeeScript's parser:

fs = require 'fs'option '-o', '--output [DIR]', 'directory for compiled code'task 'build:parser', 'rebuild the Jison parser', (options) ->
  require 'jison'
  code = require('./lib/grammar').parser.generate()
  dir  = options.output or 'lib'
  fs.writeFile "#{dir}/parser.js", code

var fs;

fs = require('fs');

option('-o', '--output [DIR]', 'directory for compiled code');

task('build:parser', 'rebuild the Jison parser', function(options) {
  var code, dir;  require('jison');
  code = require('./lib/grammar').parser.generate();
  dir = options.output || 'lib';  return fs.writeFile("" + dir + "/parser.js", code);
});

load


If you need to invoke one task before another — for example, running build before test, you can use the invoke function: invoke 'build'. Cake tasks are a minimal way to expose your CoffeeScript functions to the command line, so don't expect any fanciness built-in. If you need dependencies, or async callbacks, it's best to put them in your code itself — not the cake task.

Source Maps

CoffeeScript 1.6.1 and above include support for generating source maps, a way to tell your JavaScript engine what part of your CoffeeScript program matches up with the code being evaluated. Browsers that support it can automatically use source maps to show your original source code in the debugger. To generate source maps alongside your JavaScript files, pass the --map or -m flag to the compiler.

For a full introduction to source maps, how they work, and how to hook them up in your browser, read the HTML5 Tutorial.

"text/coffeescript" Script Tags

While it's not recommended for serious use, CoffeeScripts may be included directly within the browser using

你可能感兴趣的:(CoffeeScript)