Skip to content

CoffeeScript 速查表

可一对一编译为 JavaScript 的小型优雅语言。

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 this
02

核心特性

推导式

类似 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?()

这篇内容对您有帮助吗?