Back

把普通javascript 替换成 coffeescript的步骤

发布时间: 2012-03-16 14:41:00

注: 已经有了自动化的转换工具: js2.coffee (refer to: http://siwei.me/blog/posts/javascript-coffee-js2-coffee)

1. 重新声明方法 (this.name  or @name)
function name(para)   =>
this.name = (para) ->

( 记得 rsv 的自定义验证函数对这个有要求,都用 this.name , 否则会提示找不到函数)

2. 去掉大括号    (当传入参数大于等于1个时)
  if(true) => if true
  [a,b,c].size() => [a,b,c].size   # 绝对不可以这样做。  

例如:    [a,b,c].size() => 3

 [a,b,c].size =>  function(){ ....  }

那么在使用 if [a,b,c].size == 3 的时候,就会返回false.


3. 去掉尾部分号  ( in vim: :%s/;$ )
4. 去掉 var  (var name =1  =>  name = 1)
5. 使用 "#{}"风格的字符串连接:  
   "say"+ hi + "to" + name  
   "say#{hi}to#{name}"

6. hash:    跟JS一样,但是也可以写成下面的样子:
  a = { d:1, b: 2}  =>
  a:
    d: 1
    b: 2

7. 替换三元表达式:

  a = true ? "good" : "bad"

  a = if true then "good" else "bad"

8. 记得哦亲!有时候(似乎是声明全局method的时候) coffeescript 会从上倒下的查找方法。所以,要提前把全局方法在上面声明,然后在下面的代码中调用。否则会找不到方法哦亲!

9. 循环:

console.info("element : #{e}, index: "#{i}") for e, i in [2,3,4]

或者

for e, i in [2,3,4]
    console.info("element : #{e}, index: #{i}")

Back