是时候用Coffeescript了


CoffeeScirpt是什么?

  1. CoffeeScript是一门小巧的语言脚本语言,会编译为JavaScript,并且CoffeeScript产生的JavaScript是可以通过JavaScript Lint检测的,它的语法风格受到了Ruby和Python影响,很多特性都借鉴于这两种语言。

  2. CoffeeScript是JavaScript的子集,即众所周知的精华部分

  3. JavaScript有很多不为人知的秘密,这些秘密往往让无经验的开发者摔跤。CoffeeScript有原则地选择了一些JavaScript的特性,巧妙地避开了这些不足,解决了该语言的怪癖。

  4. 由于处理运行时错误需要JavaScript相关的知识,要写CoffeeScript还是得了解JavaScript

  5. 从经验值来看,比起纯JavaScript的话,它能减少三分之一甚至一半的代码量。还有,CoffeeScript开有一些优雅的特性,比方说列表解析、原型符号别名和类等等,能够有效的减少需要你的输入。下面左边是 CoffeeScript, 右边是编译后输出的 JavaScript.

主要特性

  1. CoffeeScript去掉了分号,它会在编译时为你自动添加

  2. CoffeeScript修复了JavaScript中一个最让人头疼的全局变量问题

  3. 函数的最后一个表达式会作为隐式的返回值。换句话说,你不再需要使用return关键字,除非你想早一点从函数中返回

  4. 支持可变参数默认参数

            times = (a = 1, b = 2) -> a * b
    
            sum = (nums...) -> 
              result = 0
              nums.forEach (n) -> result += n
              result
    
  5. 像Ruby一样,方法调用时括号也是可以省略的,但是仅限于函数被至少一个参数时,CoffeeScript会自动的调用这个函数

        alert "Hello world"
    
  6. 流程控制方面的语法糖

        if true != true then "Oh no!!"
         alert "It's cold!" if heat < 5
        unless true
          "Panic"
        if true isnt true
          alert "Opposite day!"
    
  7. 循环和列表解析

        for name in ["Roger", "Roderick", "Brian"]
          alert "Release #{name}"
    
        prisoners = ["Roger", "Roderick", "Brian"]
        release prisoner for prisoner in prisoners when prisoner[0] is "R" 
    
  8. 引入区间的概念

        firstTwo = ["one", "two", "three"][0..1]
        my = "my string"[0..2]
    
  9. 让面向对象容易

  10. 字面量

    # Without braces
    object2 = one: 1, two: 2
    # Using new lines instead of commas
    object3 = 
      one: 1
      two: 2
    
    bitlist = [
      1, 0, 1
      0, 0, 1
      1, 1, 0
    ]
    
    OPERATOR = /// ^ (
      ?: [-=]>             # 函数
       | [-+*/%<>&|^!?=]=  # 复合赋值 / 比较
       | >>>=?             # 补 0 右移
       | ([-+:])1         # 双写
       | ([&|<>])2=?      # 逻辑 / 移位
       | ?.              # soak 访问
       | .{2,3}           # 范围或者 splat
    ) ///
    
    html = """
           <strong>
             cup of coffeescript
           </strong>
           """
    
  11. 存在性探测运算符

    solipsism = true if mind? and not world?
    
    speed = 0
    speed ?= 15
    
    footprints = yeti ? "bear"
    
    zip = lottery.drawWinner?().address?.zipcode
    
  12. 运算符/比较符号
    CoffeeScript会把==操作符转化为===,把!=转化为!==。这是这门语言中我最喜欢的一个特性,也是最简单的一个

Coffeescript惯用法

  1. Each

       // ECMAScript5 的JavaScript新特性
       array.forEach(function(item, i){  
         myFunction(item)
       });
       # coffee
       myFunction(item) for item in array  
    
  2. Map

       // ECMAScript5 的JavaScript新特性
       var result = array.map(function(item, i){
         return item.name;
       });
       # coffee
       result = (item.name for item in array)
    
  3. 筛选

       // ECMAScript5 的JavaScript新特性
       result = array.filter(function(item, i){
         return item.name == "test"
       });
       #coffee
       result = (item for item in array when item.name is "test")
    
  4. And/or
    CoffeeScript编程风格推荐使用or代替||,使用and代替&&。因为前者看起来更直观。不过,这两种编程风格产生的结果都一样。

  5. is/isnt
    偏爱英语风格的代码的话,也可以使用is代替==,isnt代替!=。

       string = "migrating coconuts"
       string == string # true
       string is string # true
    
  6. 解构赋值

     theBait   = 1000
     theSwitch = 0
     
     [theBait, theSwitch] = [theSwitch, theBait]
     // ---------------------
     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
     // ---------------------
     text = "Every literary critic believes he will outwit history and have the last word"
     
     [first, ..., last] = text.split " "
     
     // ---------------------
     class Person
       constructor: (options) -> 
         {@name, @age, @height} = options
     
         tim = new Person age: 4
    

偏爱英语风格的代码的话,也可以使用is代替==,isnt代替!=。

Debug支持

Google chrome 已经率先支持coffeescript的debug。

相关杂项

  1. TypeScript

  2. Dart

  3. Move

  4. LiveScript

参考资料

  1. CoffeeScript中文手册

  2. CoffeeScript中文

  3. CoffeeScript小书

  4. TodoMVC

  5. 利用CoffeeScript创建一个类似于iOS的主屏幕

  6. Javascript Garden
    Javascript 秘密花园

  7. JavaScript: The Good Parts

  8. JavaScript Lint

原文地址:https://www.cnblogs.com/qinfanpeng/p/coffeescript_share.html