Skip to content

CoffeeScript 初体验

近期入职了一家创业公司,项目中使用了 CoffeeScript,估计很多前端的童鞋和我一样对于这门类 Javascript 预研也没啥了解,说实话,要不是团队项目中使用。我个人应该很难喜欢并使用它。闲话不多说,下面介绍一下 CoffeeScript。

CoffeeScript 是什么

CoffeeScript 是一门小巧的语言,会编译为 JavaScript 。它的语法风格受到了 Ruby 和 Python 影响,很多特性都借鉴于这两种语言。如果你对 Python 比较熟悉的话,那么一开始你绝对会喜欢 CoffeeScript,因为 CoffeeScript 的语法也是使用分号结束符与大括号代码块形式的。

初始化安装

一种尝试这个类库最简单的方式就是直接在浏览器中使用它,访问 http://coffeescript.org,点击 Try CoffeeScript 标签。这个网站使用浏览器版的 CoffeeScript 编译器,把在左边面板任意输入的 CoffeeScript 代码编译为 JavaScriprt 后显示在右边的面板中。

你也可以使用 coffee2js 项目把 JavaScript 转变为 CoffeeScirpt。这在把 JavaScript 项目迁移到 CoffeeScript 上时尤其有用。

实际上,你自己都可以使用基于浏览器的 CoffeeScirpt 编译器,只需要在页面中包含这个脚本,使用正确类型(type)的标标签记 CoffeeScript 脚本即可。

显然,在生产环境中,由于会减慢客户端的运行,所以没人愿意在运行时解释执行 CoffeeScript。作为替代,CoffeeScript 提供了一个 Node.js 版的编译器来对 CoffeeScript 文件进行预处理。这里不做详细介绍,有兴趣的朋友可以参考 http://island205.github.com/tlboc/

几个 CoffeeScript 实践

可变参数个数

CoffeeScript 允许使用可变参数个数:

coffee
mySplat = (args...) ->
    console.log "#{args.join()}"

mySplat(1,2,3,4,5)

# => 1,2,3,4,5

使用布尔型变量

coffee
lightSwitch = false

if lightSwitch is off
    console.log 'Turn on the lights!'
else
    console.log 'Turn off the lights!'

# => Turn on the lights!

存在操作符

coffee
myValue1 = 'Hello World'

if myValue1? then console.log myValue1

# This next variable doesn't exist
if myValue2? then console.log myValue2

# => Hello World

使用 in 来测试数组中是否包含某个值

通过关键字 in 你可以快速地检查数组中是否包含某个值:

coffee
foods = ['apple', 'orange', 'potatoe', 'strawberries']

if 'potatoe' in foods then console.log 'Found potatoe'
if 'carrot' in foods then console.log 'Found carrot'

# => Found potatoe

对象迭代

我们创建一个简单的对象,并展示迭代是多么的简单:

coffee
dragon =
    level: 1
    alignment: 'neutral'
    age: 'Youngling'
    attack: 'Fire'
    damage: '1d4'

for key, val of dragon
    console.log "#{key}: #{val}"

# =>
# level: 1
# alignment: neutral
# age: Youngling
# attack: Fire
# damage: 1d4

this 的快捷用法

你可以用 @ 符号来代替 this

coffee
class MyClass
    constructor: (@greeting) ->
        console.log "You set the greeting as: #{@greeting}"
    greet: ->
        console.log "You said: #{@greeting}"

myClass = new MyClass('Bonjour')
myClass.greet()

# =>
# You set the greeting as: Bonjour
# You said: Bonjour

默认值

在参数中可以设置默认值:

coffee
class MyClass
    constructor: (@greeting = 'Hola') ->
        console.log "You set the greeting as: #{@greeting}"

    greet: ->
        console.log "You said: #{@greeting}"

myClass = new MyClass()
myClass.greet()

# =>
# You set the greeting as: Hola
# You said: Hola

字符串块

如果你想对字符串进行引号和撇的快速定义,可以使用如下方法:

coffee
markup = """
    <form action="/" method="post">
        <input type="submit" />
    </form>
"""

console.log markup

# =>
# <form action="/" method="post">
#     <input type="submit" />
# </form>

字符串插值

前面很多例子中都用到了这个方法,在双引号中的所有内容都将被解析,你可以在其中嵌入某个变量:

coffee
myValue = 'Hello World'
console.log "You said: #{myValue}"

# You said: Hello World

创建一个简单的类,并演示适用构造器和继承:

coffee
class Spaceship
    constructor: (@speed  = 1, @spaceShipType = 'spaceship') ->
        console.log "New #{@spaceShipType} created with a speed of #{@speed}"

    move: () ->
        console.log "The #{@spaceShipType} is moving now at a speed of #{@speed}"

        class FlyingSaucer extends Spaceship

            constructor: ->
                super 5, 'Flying Saucer'

            useDeathRay: ->
                console.log "The flying saucer is using a death ray!"

spcshp = new Spaceship()
spcshp.move()

flySaucr = new FlyingSaucer()
flySaucr.move()
flySaucr.useDeathRay()

上次更新: