CoffeeScript 속사본
6742 단어 CoffeeScript
CoffeeScript CheetSheet
Declaration
there is no vars, and no need to add ';' and the end
i = 10
str = "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 = 10
scope = ->
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 = """
<html>
<body>
<h1>Hello World</h1>
</body>
</html>
"""
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} = options
tim = new Person age: 4
condition control
if else then
"do something" if true
if 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 != 1
countDown = (num for num in [10 .. 1] by 2)
loop an object
prints k, v for k, v of kid
print ele until ele > 10
print 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
error
finally
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 = 0
speed ?= 15
footprints = 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 = 127
healthy = 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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
laravel에 yo에서 angularJs&coffeescript를 사용할 수 있도록 한다.
먼저 yo 명령을 사용할 수 있어야하므로 아래에서 설치
global에 설치한 곳에서 laravel의 프로젝트 루트로 이동.
클라이언트 코드를 관리하는 디렉토리를 만들고 이동합니다.
클라이언트 환경 만들기
이것으로 히...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.
i = 10
str = "hello world"
[firstName, lastName] = ["kang", "wang"]
fn = (param) - ...
fn = (parm1, parm1, params...) ->
...
params = ["value1", "value2", "value3", "value4"]
fn(params)
fn("value", params)
fn("value", "value", params)
arr = [
"element1"
"element2"
]
obj =
first: 1
second:
second_1: 1
second_2: 2
third: 3
$('.element').attr class: "active"
outter = 10
scope = ->
inner = 10
inner = 20
str = "variable 1: #{var1}, function 1 returns: #{fn()}"
str = "
today is Sunday
so tomorrow is
Monday
"
htmlTpl = """
<html>
<body>
<h1>Hello World</h1>
</body>
</html>
"""
[var1, var2] = [value1, value2]
{firstName, lastName} = {firstName: "Kang", lastName: "Wang"}
location () ->
["US", "LA", "Berkly"]
[county, province, city] = location()
[start, end] = "hello, world".split ","
[start, ..., end] = [1, 2, 3, 4, 5]
class Person
constructor: (options) ->
{@name, @age, @height} = options
tim = new Person age: 4
"do something" if true
if true and true
"do something"
else
"do other things"
if true then "do something" else "do other things"
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 != 1
countDown = (num for num in [10 .. 1] by 2)
prints k, v for k, v of kid
print ele until ele > 10
print ele while ele > 10
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
fn(1)
catch error
error
finally
then
numSerials = [10 .. 0]
start = numSerials[0..2]
end = numSerials[0..-2]
end = numSerials[..]
umSerials[0..2] = [1, 2, 3]
globals = (name for name of window)[0...10]
solipsism = true if mind? and world?
speed = 0
speed ?= 15
footprints = yeti ? "bear"
kid.brother?.sister
switch day
when "Mon" then ""
when "Tue" then ""
else "WTF"
day = switch day
when "Mon" then ""
when "Tue" then ""
else "WTF"
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
Array::map = ->
"..."
cholesterol = 127
healthy = 200 > cholesterol > 60
OPERATOR = /// ^ (
?: [-=]> # function
| [-+*/%<>&|^!?=]= # compound assign / compare
| >>>=? # zero-fill right shift
| ([-+:])\1 # doubles
| ([&|<>])\2=? # logic / shift
| \?\. # soak access
| \.{2,3} # range or splat
) ///
fn = `function fn() {}`
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
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
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
laravel에 yo에서 angularJs&coffeescript를 사용할 수 있도록 한다.먼저 yo 명령을 사용할 수 있어야하므로 아래에서 설치 global에 설치한 곳에서 laravel의 프로젝트 루트로 이동. 클라이언트 코드를 관리하는 디렉토리를 만들고 이동합니다. 클라이언트 환경 만들기 이것으로 히...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.