01
快速上手
Hello World
函数调用的括号可以省略。
coffeescript
console.log "Hello, World!"变量
没有 var/let/const——变量自动管理作用域。
coffeescript
x = 10
y = 20
console.log x + y函数
-> 定义函数;最后一个表达式作为返回值。
coffeescript
add = (a, b) -> a + b
console.log add 3, 4
square = (n) -> n * n胖箭头
=> 把 'this' 绑定到定义时的作用域。
coffeescript
this.handler = =>
console.log this02
核心特性
推导式
类似 Python 的列表推导式。
coffeescript
squares = (n * n for n in [1..5])
evens = (n for n in [1..10] when n % 2 == 0)解构
支持对象和数组的解构。
coffeescript
{name, age} = person
[first, rest...] = array类
类语法,用 @ 表示 this。
coffeescript
class Animal
constructor: (@name) ->
speak: -> console.log @name
class Dog extends Animal
speak: -> console.log "#{@name} says woof"存在性检查
? 检查是否存在;?. 用于安全链式调用。
coffeescript
if name? then greet name
result = obj?.property?.method?()这篇内容对您有帮助吗?