CoffeeScript 是一门编译到 JavaScript 的小巧语言. 在 Java 般笨拙的外表下, JavaScript 其实有着一颗华丽的心脏. CoffeeScript 尝试用简洁的方式展现 JavaScript 优秀的部分.javascript
CoffeeScript 的指导原则是: "她仅仅是 JavaScript". 代码一一对应地编译到 JS, 不会在编译过程当中进行解释. 已有的 JavaScript 类库能够无缝地和 CoffeeScript 搭配使用, 反之亦然. 编译后的代码是可读的, 且通过美化, 能在全部 JavaScript 环境中运行, 而且应该和对应手写的 JavaScript 同样快或者更快.php
最新版本: 1.7.1html
sudo npm install -g coffee-script
左边是 CoffeeScript, 右边是编译后输出的 JavaScript.java
# 赋值: number = 42 opposite = 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; })();
CoffeeScript 编译器自己是 CoffeeScript 写的, 使用了 Jison parser generator. 命令行版本的 coffee 是一个实用的 Node.js 工具. 不过编译器并不依赖 Node, 而是能运行于任何 JavaScript 执行环境, 好比说在浏览器里(看上边的"试一试 CoffeeScript").node
安装前你须要最新稳定版 Node.js, 和 npm (Node Package Manager). 借助 npm 能够安装 CoffeeScript:python
npm install -g coffee-script
(若是不想全局安装能够去掉 -g 选项.)git
若是你但愿安装 master 分支上最新的 CoffeeScript, 你能够从源码仓库 克隆 CoffeeScript, 或直接下载源码. 还有经过 npm 方式安装 master 分支最新的 CoffeeScript 编译器:github
npm install -g http://github.com/jashkenas/coffee-script/tarball/master
或者你想将其安装到 /usr/local, 而不用 npm 进行管理, 进入 coffee-script 目录执行:web
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 来传递多个参数. |
例子:
除了被做为一个普通的编程语言, 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 * x cube = (x) -> square(x) * x
var cube, square; square = function(x) { return x * x; }; cube = function(x) { return square(x) * x; };
一些函数函数参数会有默认值, 当传入的参数的不存在 (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 + "..."; };
对象和数组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 } };
JavaScript 里, 你不能使用不添加引号的保留字段做为属性名称, 好比 class. CoffeeScript 里做为键出现的保留字会被识别并补上引号, 因此你不用有额外的操心(好比说, 使用 jQuery 的时候).
$('.account').attr class: 'active' log object.class
$('.account').attr({ "class": 'active' }); log(object["class"]);
词法做用域和变量安全CoffeeScript 编译器会考虑全部变量, 保证每一个变量都在词法域里适当地被定义 — 你永远不须要本身去写 var.
outer = 1 changeNumbers = -> inner = -1 outer = 10 inner = changeNumbers()
var changeNumbers, inner, outer; outer = 1; changeNumbers = function() { var inner; inner = -1; return outer = 10; }; inner = changeNumbers();
注意全部变量的定义都被推到相关的顶层做用域, 也就是第一次出现的位置. 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 singing if 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;
变参(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);
循环和推导式你可使用CoffeeScript将大多数的循环写成基于数组、对象或范围的推导式(comprehensions)。 推导式替代(编译为)for循环,而且可使用可选的子句和数组索引值。 不一样于for循环,数组的推导式是表达式,能够被返回和赋值。
# 吃午餐. 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); } }
推导式能够适用于其余一些使用循环的地方,例如each/forEach, map,或者select/filter,例如:shortNames = (name for name in list when name.length < 5)
若是你知道循环的开始与结束,或者但愿以固定的跨度迭代,你能够在范围推导式中 指定开始与结束。
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; })();
注意:上面的例子中咱们展现了如何将推导式赋值给变量,CoffeeScript老是将 每一个循环项收集到一个数组中。可是有时候以循环结尾的函数运行的目的就是 它们的反作用(side-effects)。这种状况下要注意不要意外的返回推导式的结果, 而是在函数的结尾增长一些有意义的返回值—例如true — 或 null。
在推导式中使用by子句,能够实现以固定跨度迭代范围值: evens = (x for x in [0..10] by 2)
推导式也能够用于迭代对象中的key和value。在推导式中使用of 来取出对象中的属性,而不是数组中的值。
yearsOld = max: 10, ida: 9, tim: 11 ages = 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; })();
若是你但愿仅迭代在当前对象中定义的属性,经过hasOwnProperty检查并 避免属性是继承来的,能够这样来写:
for own key, value of object
CoffeeScript仅提供了一种底层循环,即while循环。与JavaScript中的while 循环的主要区别是,在CoffeeScript中while能够做为表达式来使用, 并且能够返回一个数组,该数组包含每一个迭代项的迭代结果。
# 经济 101 if this.studyingEconomics buy() while supply > demand sell() until supply > demand # 摇篮曲 num = 6 lyrics = 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; })();
为了更好的可读性,until关键字等同于while not, loop关键字 等同于while true。
使用 JavaScript 循环生成函数的时候, 常常会添加一个闭包来包裹代码, 这样作目的是为了循环的变量被保存起来, 而不是全部生成的函数搜去访问最后一个循环的变量. CoffeeScript 提供了一个 do 关键字, 用来直接调用跟在后边的函数, 而且传递须要的参数.
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); }
数组的切片和用 range 进行拼接Range 也能够被用来展开数组的切片. 经过两个点号的写法 (3..6), range 会包含最后一个数据 (3, 4, 5, 6); 经过三个点号的写法 (3...6), range 不会包含最后一个数据 (3, 4, 5). 切片的索引位置存在不错的默认值. 前面的索引位置省略的话, 默认会是 0, 后面的索引位置被省略的话, 默认值是数组的大小.
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);
一样的语法还能够用在数组的片断上赋值一些新的值, 进行拼接.
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;
注意 JavaScript 的 string 是不可变的, 因此不能用被拼接.
一切都是表达式 (至少尽量成为)读者大概有注意到上面的代码 CoffeeScript 函数是不须要写 return 语句的, 可是也会返回最终的结果. CoffeeScript 编译器会尽量保证语言中全部的表达式均可以被看成表达式使用. 观察一下下面的函数, return 是怎样尽量地插入到执行的分支当中的.
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";
尽管函数老是会自动 return 其最终的值, 你能够在函数体前面显式地写上 (return value), 这个作法也是值得借鉴的, 前提是你明确你在作的事情是什么.
因为变量声明是生成在做用域顶部, 因此在表达式内部也能够写赋值, 即使是前面没写到过的变量.
six = (one = 1) + (two = 2) + (three = 3)
var one, six, three, two; six = (one = 1) + (two = 2) + (three = 3);
有些代码在 JavaScript 当中要写很多的语句, 而在 CoffeeScript 中只是表达式的一部分, 这些代码的编译结果会自动生成一个闭包. 这个写法颇有用, 好比把列表解析的结果赋值给变量:
# 前十个全局属性(变量). 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);
结果是一些原来明确是语句的东西也能够像, 好比把 try/catch 语句直接传给函数调用:
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; } })());
有一些 JavaScript 语句是不能编译到表达式的对应的语义的, 好比 break, continue 和 return. 若是你的代码当中用到了它们, CoffeeScript 是步骤尝试去进行转换的.
操做符和 aliase因为操做符 == 经常带来不许确的约束, 不容易达到效果, 并且跟其余语言当中意思不一致, CoffeeScript 会把 == 编译为 ===, 把 != 变异为 !==. 此外, is 编译我 ===, 而 isnt 编译为 !==.
not 能够做为 ! 的 alias 使用.
逻辑操做方面, and 编译为 &&, 而 or 编译为 ||.
在 while, if/else, switch/when 的语句当中, then 能够被用来分隔判断条件跟表达式, 这样就不用强制写换行或者分号了.
就像 YAML, on 和 yes 跟 true 是同样的, 而 off 和 no 是布尔值 false.
unless 能够认为是 if 相反的版本.
this.property 简短的写法能够用 @property.
能够用 in 判断数据在数组中是否出现, 而 of 能够探测 JavaScript 对象的属性是否存在.
为了简化数学表达式, ** 能够用来表示乘方, // 表示整除, %% 提供数学的模运算(译注: true mathematical modulo?).
完整的列表:
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 on volume = 10 if band isnt SpinalTap letTheWildRumpusBegin() unless answer is no if 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));
存在性操做符在 JavaScript 里检测一个变量的存在性有点麻烦. if (variable) ... 比较接近答案, 可是对 `0` 不成立. CoffeeScript 的存在性操做符 ? 除非是 null 或者 undefined, 不然都返回 true, 这大体是模仿 Ruby 当中的 nil?.
这也能够用在比 ||= 更安全的条件赋值当中, 有些状况你会须要处理数字跟字符串的.
solipsism = true if mind? and not world? speed = 0 speed ?= 15 footprints = 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";
存在性操做符 ?. 的访问器的变体能够用来吸取链式属性调用中的 null. 数据多是 null 或者undefined 的状况下能够用这种写法替代访问器 .. 若是全部属性都存在, 那么你会获得想要的结果, 若是链式调用有问题, 会返回 undefined 而不是抛出 TypeError.
zip = lottery.drawWinner?().address?.zipcode
var zip, _ref; zip = typeof lottery.drawWinner === "function" ? (_ref = lottery.drawWinner().address) != null ? _ref.zipcode : void 0 : void 0;
吸取 null 数据的作法相似 Ruby 的 andand gem, 和 Groovy 的 safe navigation operator.
class, 继承, superJavaScript 的原型集成有点烧脑, 存在大量的类库用于在 JavaScript 的原型之上实现更清晰的 class 继承好比: Base2, Prototype.js, JS.Class. 这些类库提供了语法糖, 但若是不是由于一些例外的话原生的继承彻底是可用的, 例外好比: 很难调用 super(当前函数的原型上的实现), 很难正确设置原型链.
相比重复地设置函数的原型, CoffeeScript 提供了一个基础的 class 结构, 你能够在一个定义的表达式里完成命名 class, 定义父类, 赋值原型上的属性, 定义构造器.
构造函数被命名, 这对查看调用栈有更好的支持. 下面例子中的第一个类, this.constructor.name is "Animal".
class Animal constructor: (@name) -> move: (meters) -> alert @name + " moved #{meters}m." class Snake extends Animal move: -> alert "Slithering..." super 5 class Horse extends Animal move: -> alert "Galloping..." super 45 sam = 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();
若是你不喜欢用 class 的裁判法定义原型, CoffeeScript 提供了一些低级的方便写法. extends 操做符能够用来恰当地定义任何一对构造函数的原型链; 用 :: 能够快速访问对象的原型; super() 能够编译为一个父类上同名方法的调用.
String::dasherize = -> this.replace /_/g, "-"
String.prototype.dasherize = function() { return this.replace(/_/g, "-"); };
最后, class 定义是可执行的代码, 这样就可能进行元编程. 由于在 class 定义的上下文当中, this 是类对象自己(构造函数), 能够用 @property: value 赋值静态的属性, 也能够调用父类的方法: @attr 'title', type: 'text'.
解构赋值CoffeeScript 实现 ECMAScript Harmony 的提议 解构赋值 语法, 这样从复杂的数组和对象展开数据会更方便一些. 当你把数组或者对象的字面量赋值到一个变量时, CoffeeScript 把等式两边都解开配对, 把右边的值赋值给左边的变量. 最简单的例子, 能够用来并行赋值:
theBait = 1000 theSwitch = 0 [theBait, theSwitch] = [theSwitch, theBait]
var theBait, theSwitch, _ref; theBait = 1000; theSwitch = 0; _ref = [theSwitch, theBait], theBait = _ref[0], theSwitch = _ref[1];
用来处理函数多返回值也很方便.
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];
解构赋值能够用在深度嵌套的数组跟对象上, 取出深度嵌套的属性.
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]);
解构赋值还能够跟 splats 搭配使用.
tag = "<impossible>" [open, contents..., close] = tag.split("")
var close, contents, open, tag, _i, _ref, __slice = [].slice; tag = "<impossible>"; _ref = tag.split(""), open = _ref[0], contents = 3 <= _ref.length ? __slice.call(_ref, 1, _i = _ref.length - 1) : (_i = 1, []), close = _ref[_i++];
展开式(expansion)能够用于获取数组结尾的元素, 而不须要对中间过程的数据进行赋值. 它也能够用在函数参数的列表上.
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];
解构赋值也能够用在 class 的构造器上, 从构造器配置对象赋值到示例属性上.
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 });
函数绑定JavaScript 当中 this 关键字被动态地设定为当前函数挂载所在的对象上. 若是你把函数看成回调, 或者挂载到别的对象, 那么原先的 this 就丢失了. 若是你不了解这个行为, If you're not familiar with this behavior, this Digital Web article 对怪异模式作了很好的回顾.
Fat arrow => 能够同时定义函数, 绑定函数的 this 到当前的值, 正是咱们须要的. 这有助于在 Prototype 或者 jQuery 这种基于回调的类库当中使用, 用于建立迭代器函数传递给 each, 或者借助 bind 的事件处理器函数. Fat arrow 定义的函数能够访问到他们建立位置的 this 对象的属性.
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)); };
若是上边用的是 this, @customer 会指向一个 DOM 元素的 undefined "customer" 属性, 而后强行调用上面的 purchase() 时会抛出一个异常.
对于类的定义, 实例建立的过程当中 fat arrow 定义的方法会自动绑定到类的每一个示例上去.
嵌入 JavaScript这个写法应该不会被用到, 但若是何时须要在 CoffeeScript 中穿插 JavaScript 片断的话, 你能够用反引号直接传进去.
hi = `function() { return [document.title, "Hello JavaScript"].join(": "); }`
var hi; hi = function() { return [document.title, "Hello JavaScript"].join(": "); };
Switch/When/ElseJavaScript 里的 Switch 语句有点难看. 你须要在每一个 case 写 break 防止自动进入默认的 case. CoffeeScript 会阻止掉意外的 fall-through. 并且 switch 编译的结果会是能够带 return, 能够被用于赋值的表达式. 格式这样写: switch 判断条件, when 而后子句, else 而后默认的 case.
就像 Ruby, CoffeeScript 里边 switch 语句对于每一个子句能够带多个值. 任何一个值匹配的状况下, 子句就会执行.
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); }
Switch 语句也能够不写控制条件, 看成 if/else 调用链的一个更整洁的可选写法.
score = 76 grade = 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'; } })();
Try/Catch/FinallyTry/catch 语句基本上 JavaScript 的同样(尽管它们是表达式执行).
try allHellBreaksLoose() catsAndDogsLivingTogether() catch error print error finally cleanUp()
var error; try { allHellBreaksLoose(); catsAndDogsLivingTogether(); } catch (_error) { error = _error; print(error); } finally { cleanUp(); }
Chained ComparisonsCoffeeScript 从 Python 学习了 链式对比 — 这样判断数值是否在某个范围内在写法上更容易.
cholesterol = 127 healthy = 200 > cholesterol > 60
var cholesterol, healthy; cholesterol = 127; healthy = (200 > cholesterol && cholesterol > 60);
字符串替换, 块级的字符串, 块级的注释Ruby 风格的字符串替换也在 CoffeeScript 实现了. 双引号包裹的字符串容许数据替换, 用 #{ ... }语法, 而单引号包裹的字符串仅仅是字面量.
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 π";
CoffeeScript 支持多行字符串. 行与行会用一个空格拼接, 除非结尾用了反斜杠. 其中缩进会被忽略.
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...";
块级的字符串能够用于书写格式化的或者对缩进敏感的文本(或者你只是不想转义单引号双引号). 代码块开始的位置的缩进层级会被保留, 用在后面的代码中, 因此这部分代码依然能够跟总体的代码一块儿对齐.
html = """ <strong> cup of coffeescript </strong> """
var html; html = "<strong>\n cup of coffeescript\n</strong>";
块级的字符串用双引号, 跟普通的双引号字符串同样, 支持替换.
有时候你想把整块的注释传给生成的 JavaScript. 好比在文件顶部嵌入协议. 块级的注释, 仿照了块级字符串的语法, 将会在生成的代码当中保留.
### SkinnyMochaHalfCaffScript Compiler v1.0 Released under the MIT License ###
/* SkinnyMochaHalfCaffScript Compiler v1.0 Released under the MIT License */
块级的正则表达式相似块级的字符串跟注释, CoffeeScript 支持块级的正则 — 扩展了正则表达式, 能够忽略内部的空格, 能够包含注释和替换. 模仿了 Perl 的 /x 修饰符, CoffeeScript 的块级正则以 /// 为界, 让正则表达式得到了很大程度的可读性. 引用一下 CoffeeScript 源码:
OPERATOR = /// ^ ( ?: [-=]> # 函数 | [-+*/%<>&|^!?=]= # 复合赋值 / 比较 | >>>=? # 补 0 右移 | ([-+:])\1 # 双写 | ([&|<>])\2=? # 逻辑 / 移位 | \?\. # soak 访问 | \.{2,3} # 范围或者 splat ) ///
var OPERATOR; OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3})/;
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); });
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.