CoffeeScript示例(几乎涵盖所有语法)
博客专区 > WolfX 的博客 > 博客详情
CoffeeScript示例(几乎涵盖所有语法)
WolfX 发表于2年前
CoffeeScript示例(几乎涵盖所有语法)
  • 发表于 2年前
  • 阅读 40
  • 收藏 1
  • 点赞 1
  • 评论 0

华为云·免费上云实践>>>   

#数组
song = ["do", "re", "mi", "fa", "so"]
bitlist = [
  1, 0, 1
  0, 0, 1
  1, 1, 0
]
#对象
singers = {Jagger: "Rock", Elvis: "Roll"}
kids =
  brother:
    name: "Max"
    age:  11
  sister:
    name: "Ida"
    age:  9

#词法作用域和变量安全
outer = 1 #在最外面创建了一个outer
changeNumbers = ->
  inner = -1 #在内部创建了inner
  outer = 10 #赋值给外部的outer
inner = changeNumbers() #创建了外部的inner,并赋予方法

#if, else, unless 和条件赋值
mood = greatlyImproved if singing #如果singing是true,mood=greatlyImproved
if happy and knowsIt
  clapsHands()
  chaChaCha()
else
  showIt()
date = if friday then sue else jill #date = friday ? sue : jill

#变参(splats)...
gold = silver = rest = "unknown"
awardMedals = (first, second, others...) ->
  gold   = first
  silver = second
  rest   = others
  
#循环和推导式
eat food for food in ['toast', 'cheese', 'wine'] #遍历数组,每个元素作为food,并且执行eat(food)

courses = ['greens', 'caviar', 'truffles', 'roast', 'cake']
menu i + 1, dish for dish, i in courses #遍历courses,每个元素作为dish,循环次数为i,且执行menu(i+1,dish)

foods = ['broccoli', 'spinach', 'chocolate']
eat food for food in foods when food isnt 'chocolate' #遍历数组,每个元素作为food,当food!='chocolate'时执行eat(food)

if this.studyingEconomics
  buy()  while supply > demand
  sell() until supply > demand
  
num = 6
lyrics = while num -= 1
  "#{num} little monkeys, jumping on the bed.
    One fell out and bumped his head."
    
for filename in list
  do (filename) ->
    fs.readFile filename, (err, contents) ->
      compile filename, contents.toString()
      
#数组的切片和用 range 进行拼接
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
start   = numbers[0..2] #numbers.slice(0, 3);
middle  = numbers[3...-2] #numbers.slice(3, -2);
end     = numbers[-2..] #numbers.slice(-2);
copy    = numbers[..] #numbers.slice(0);

#一切都是表达式 (至少尽可能成为)
alert(
  try
    nonexistent / undefined
  catch error
    "And the error is ... #{error}"
)

# 由于操作符 == 常常带来不准确的约束, 不容易达到效果, 而且跟其他语言当中意思不一致, CoffeeScript 会把 == 编译为 ===, 把 != 变异为 !==. 此外, is 编译我 ===, 而 isnt 编译为 !==.
# not 可以作为 ! 的 alias 使用.
# 逻辑操作方面, and 编译为 &&, 而 or 编译为 ||.
# 在 while, if/else, switch/when 的语句当中, then 可以被用来分隔判断条件跟表达式, 这样就不用强制写换行或者分号了.
# 就像 YAML, on 和 yes 跟 true 是一样的, 而 off 和 no 是布尔值 false.
# unless 可以认为是 if 相反的版本.
# this.property 简短的写法可以用 @property.
# 可以用 in 判断数据在数组中是否出现, 而 of 可以探测 JavaScript 对象的属性是否存在.
# 为了简化数学表达式, ** 可以用来表示乘方, // 表示整除, %% 提供数学的模运算(译注: true mathematical modulo?). 
CoffeeScript	#JavaScript
is	#===
isnt	#!==
not	#!
and	#&&
or	#||
true, yes, on #	true
false, no, off	#false
@, this	#this
of	#in
in	#no JS equivalent
a ** b	#Math.pow(a, b)
a // b	#Math.floor(a / b)
a %% b	#(a % b + b) % b

#存在性操作符
solipsism = true if mind? and not world? #判断对象的存在性
zip = lottery.drawWinner?().address?.zipcode #判断链式语法中对象的存在性

#class, 继承, super
class Animal
  constructor: (@name) ->

  move: (meters) ->
    alert @name + " moved #{meters}m."

class Snake extends Animal
  move: ->
    alert "Slithering..."
    super 5

class Horse extends Animal
  move: ->
    alert "Galloping..."
    super 45

sam = new Snake "Sammy the Python"
tom = new Horse "Tommy the Palomino"

sam.move()
tom.move()



String::dasherize = -> #快速访问String.prototype.dasherize
  this.replace /_/g, "-"


#解构赋值
[theBait, theSwitch] = [theSwitch, theBait] #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 #name=futurists.poet.name...

text = "Every literary critic believes he will
        outwit history and have the last word"
[first, ..., last] = text.split " "

#解构赋值,可用于class的构造器上
class Person
  constructor: (options) -> 
    {@name, @age, @height} = options
tim = new Person age: 4


#函数绑定
Account = (customer, cart) ->
  @customer = customer
  @cart = cart

  $('.shopping_cart').bind 'click', (event) =>
    @customer.purchase @cart
    
    
#嵌入 JavaScript;这个写法应该不会被用到, 但如果什么时候需要在 CoffeeScript 中穿插 JavaScript 片段的话, 你可以用反引号直接传进去. 
hi = `function() {
  return [document.title, "Hello JavaScript"].join(": ");
}`

#Switch/When/Else
switch day
  when "Mon" then go work
  when "Tue" then go relax
  when "Thu" then go iceFishing
  when "Fri", "Sat"
    if day is bingoDay
      go bingo
      go dancing
  when "Sun" then go church
  else go work

#可以不写控制条件
score = 76
grade = switch
  when score < 60 then 'F'
  when score < 70 then 'D'
  when score < 80 then 'C'
  when score < 90 then 'B'
  else 'A'
# grade == 'C'


#Try/Catch/Finally
try
  allHellBreaksLoose()
  catsAndDogsLivingTogether()
catch error
  print error
finally
  cleanUp()
  
#字符串替换, 块级的字符串, 块级的注释
author = "Wittgenstein"
quote  = "A picture is a fact. -- #{ author }"
sentence = "#{ 22 / 7 } is a decent approximation of π"

#链式对比
healthy = 200 > cholesterol > 60 #healthy = (200 > cholesterol && cholesterol > 60);

#CoffeeScript 支持多行字符串. 行与行会用一个空格拼接, 除非结尾用了反斜杠. 其中缩进会被忽略. 
mobyDick = "Call me Ishmael. Some years ago --
  never mind how long precisely -- having little
  or no money in my purse, and nothing particular
  to interest me on shore, I thought I would sail
  about a little and see the watery part of the
  world..."

#块级的字符串
html = """
       <strong>
         cup of coffeescript
       </strong>
       """
       

###
块级注释
SkinnyMochaHalfCaffScript Compiler v1.0
Released under the MIT License
###


#块级的正则表达式
OPERATOR = /// ^ (
  ?: [-=]>             # 函数
   | [-+*/%<>&|^!?=]=  # 复合赋值 / 比较
   | >>>=?             # 补 0 右移
   | ([-+:])\1         # 双写
   | ([&|<>])\2=?      # 逻辑 / 移位
   | \?\.              # soak 访问
   | \.{2,3}           # 范围或者 splat
) ///
标签: CoffeeScript
共有 人打赏支持
WolfX
粉丝 53
博文 246
码字总数 31477
×
WolfX
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: