博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
CoffeeScript 速抄本
阅读量:6260 次
发布时间:2019-06-22

本文共 4591 字,大约阅读时间需要 15 分钟。

hot3.png

CoffeeScript CheetSheet#

Declaration

there is no vars, and no need to add ';' and the end

i = 10str = "hello world"[firstName, lastName] = ["kang", "wang"]

define a function, no need to add the keyword 'function', -> is enough

fn = (param) -  ...

Splats: define a function with multi parameters

fn = (parm1, parm1, params...) ->    ...params = ["value1", "value2", "value3", "value4"]fn(params)fn("value", params)fn("value", "value", params)

define an Array

arr = [   "element1"   "element2"]

define an object

obj =    first: 1   second:       second_1: 1      second_2: 2   third: 3$('.element').attr class: "active"

lexical scoping and variable safity.

outter = 10scope = ->   inner = 10

outter = 20 inner = 20

String Interpolation

mixin variable and function in string defination

str = "variable 1: #{var1}, function 1 returns: #{fn()}"str = "   today is Sunday   so tomorrow is    Monday"htmlTpl = """                  

Hello World

"""

Destructuring Assignment

[var1, var2] = [value1, value2]

use on object unapply

{firstName, lastName} = {firstName: "Kang", lastName: "Wang"}

use for a function multi-returns

location () ->      ["US", "LA", "Berkly"][county, province, city] = location() [start, end] = "hello, world".split ","

use to skip some useless bucket ...

[start, ..., end] = [1, 2, 3, 4, 5]

destructuring constructor

class Person   constructor: (options) ->   {@name, @age, @height} = optionstim = new Person age: 4

condition control

if else then

"do something" if trueif true and true    "do something"else    "do other things"if true then "do something" else "do other things"

for loop control

for loop while until

print ele for ele in [1, 2, 3, 4]prints i, ele for ele in [1, 2, 3, 4]print ele for ele in [1, 2, 3, 4] when ele / 2 != 1countDown = (num for num in [10 .. 1] by 2)

loop an object

prints k, v for k, v of kidprint ele until ele > 10print ele while ele > 10

do keywords

for filename in list   do (filename) ->      fs.readFile filename, (err, contents) ->         compile filename, contents.toString()for ele in [1, 2, 3, 4]   do print ele

try .. catch .. expression

try 	  fn(1)catch error	  errorfinally	  then

try .. catch .. expression

Array Operations

numSerials = [10 .. 0]start = numSerials[0..2]end = numSerials[0..-2]end = numSerials[..]umSerials[0..2] = [1, 2, 3]

use expression as much as possible

globals = (name for name of window)[0...10]

Existantial Operator ?, ?.

'?' means varaible is null or undefiend

solipsism = true if mind? and world?speed = 0speed ?= 15footprints = yeti ? "bear"

'?.' usef for assessing object attribute

kid.brother?.sister

switch when else

switch day 	when "Mon" then "" 	when "Tue" then "" 	else "WTF" day = switch day 	when "Mon" then "" 	when "Tue" then "" 	else "WTF"

object oriented

use => to bind this in scope

Account = (customer, cart) ->   @customer = customer   @cart = cart    $('.shopping_cart').bind 'click', (event) =>     @customer.purchase @cart Account2 = (customer, cart) ->   @customer = customer   @cart = cart    $('.shopping_cart').bind 'click', (event) ->     @customer.purchase @cart

bind function to an exists function

Array::map = ->   "..."

some sugar

chained comparasion

cholesterol = 127healthy = 200 > cholesterol > 60

block regular expression

OPERATOR = /// ^ (  ?: [-=]>             # function   | [-+*/%<>&|^!?=]=  # compound assign / compare   | >>>=?             # zero-fill right shift   | ([-+:])\1         # doubles   | ([&|<>])\2=?      # logic / shift   | \?\.              # soak access   | \.{2,3}           # range or splat) ///

embeded javascript

fn = `function fn() {}`

operators and alias in CoffeeScript

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

multi etends example

moduleKeywords = ['extended', 'included']  class Trait 	@mixin: (obj) =>    		for key, value of obj when key not in moduleKeywords 			@::[key] = value		  		obj.with?.apply(@) 		this  	@with: (objs ...) -> 		@mixin obj for obj in objs   MongoDao = 	find: () -> console.log("find items in mongo")  	create: () -> console.log("delete item in mongo")  class UserDao extends Trait  	@with Daoable, MongoDao

转载于:https://my.oschina.net/u/217548/blog/398992

你可能感兴趣的文章
【OC语法要闻速览】一、方法调用
查看>>
Git-命令行-删除本地和远程分支
查看>>
本文将介绍“数据计算”环节中常用的三种分布式计算组件——Hadoop、Storm以及Spark。...
查看>>
顺序图【6】--☆☆
查看>>
Docker Swarm 让你事半功倍
查看>>
[转]IC行业的牛人
查看>>
javaScript事件(四)event的公共成员(属性和方法)
查看>>
linux系统常用命令
查看>>
在 Word 中的受支持的区域设置标识符的列表
查看>>
Caffe + Ubuntu 14.04 64bit + CUDA 6.5 配置说明2
查看>>
An easy to use android color picker library
查看>>
Oracle SID爆破工具SidGuess
查看>>
批处理常用命令总结2
查看>>
解读ASP.NET 5 & MVC6系列(9):日志框架
查看>>
Android -- 自定义View小Demo,绘制钟表时间(一)
查看>>
信息检索Reading List
查看>>
JavaWeb_JavaEE_命名规则
查看>>
申小雨命案审理延期至3月5日 警方将翻译嫌犯口供
查看>>
自动精简配置&重复数据删除核心技术点及其经济效应探究
查看>>
cncert网络安全周报35期 境内被植入后门的政府网站112个 环比上涨24.4%
查看>>