您的位置:首页 > Web前端

coffeeScript学习01

2015-03-25 11:22 120 查看

安装

这里使用node.js

npm install -g coffee-script
# watch and compile
coffee -w --output lib --compile src
//
coffee -w -c index.coffee

语法

CoffeeScript不是JavaScript的超集,不能在CoffeeScript程序中写JavaScript代码

格式

CoffeeScript在编译时为每条语句加上;

CoffeeScript中的注释采用#

作用域

会自动添加变量声明‘var’,放到作用域的顶部

赋值

字符串可以用类ruby的语法内嵌

target = "world"
alert "hello, #{target}"    //注意双引号
alert "hello" + target


字面量

object1 = one: 1, two: 2
object2 =
one: 1
two: 2
arr1 = [1, 2]
arr2 = [
1,
2
]


解构赋值

obj = {a:"foo", b:"bar"}
{a, b} = obj
arr = [1, 2]
[a, b] = arr

数组

数组的操作引入了来自ruby的Range概念,并且可以将字符串完全作为数组操作

numbers = [0..9]  //两个或三个点号
numbers[3..5] = [-3,-4,-5]   //替换number 3-5的值;可以是任意个数
my = "my string"[0..1]


判断一个值是否在数组内

arr = ["foo", "bar"]
"foo" in arr


for..in语法

for name, i in ["roger", "roderick"]
alert "#{i} - Release #{name}"


过滤器when

items = ["ranger", "roderick", "brian"]
alert 'ok' for item in items when item is "ranger"


可以用()收集遍历的结果

items = [{id: 0, name: "ranger"}, {id: 1, name: "roderick"}, {id: 2, name: "brian"}]
result = (item for item in items when item.id is 1)   //注意前面有个item;以数组形式返回

流程控制

函数

CoffeeScript对JavaScript的函数做了很大的简化

sum = (nums) ->
nums.reduce(x, y) -> x + y

sum 1,2,3

//
(function() {
var sum;

sum = function(nums) {
return nums.reduce(x, y)(function() {
return x + y;
});
};

sum(1, 2, 3);

}).call(this);


->来代替function; 注意前面空一格

参数列表放在->的前边,且可省略

取消了函数声明,只能将函数作为值定义

在CoffeeScript中,任何语句都是表达式(除了break和continue),都有返回值,因此像ruby一样,不需要显式return

CoffeeScript的函数可以有默认参数

times = (a = 1, b = 2) -> a * b


CoffeeScript的函数调用可以不用()语法包围参数,像ruby一样跟在函数名后面就可以,不过这也有时候会带来问题,特别是没有参数的调用

缩进的格式有时需要小心,比如用多个函数做参数的时候

$(".toggle").toggle ->
"on"
, ->
"off"

//
(function() {
$(".toggle").toggle(function() {
return "on";
}, function() {
return "off";
});

}).call(this);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: