CoffeeScript 函数
本教程的语法规则基于CoffeeScript 1.7.1版本。
首先, 基础的语法规则是, CoffeeScript 使用显式的空白来区分代码块。这意味着你不需要使用分号 “;” 来关闭表达式, 在一行的结尾换行就可以了(尽管分号依然可以用来把多行的表达式简写到一行里)。 不需要再用花括号来{ } 包裹代码快, 在 函数、if 表达式、switch和try/catch中使用缩进来代替花括号。这些特征和Python很类似。
传入参数的时候, 你不需要再使用圆括号来表明函数被执行,
隐式的函数调用的作用范围一直到行尾或者一个块级表达式。
console.log sys.inspect object → console.log(sys.inspect(object));
函数 函数通过一组可选的圆括号包裹的参数, 一个箭头, 一个函数体来定义. 一个空的函数像是这样: ->
CoffeeScript:编译成JS后是这样的:
- square = (x) -> x * x
- cube = (x) -> square(x) * x
- var cube, square;
- square = function(x) {
- return x * x;
- };
- cube = function(x) {
- return square(x) * x;
- };
一些函数函数参数会有默认值, 当传入的参数的不存在 (null 或者 undefined) 时会被使用:
CoffeeScript:JS:
- fill = (container, liquid = "coffee") ->
- "Filling the #{container} with #{liquid}..."
- var fill;
- fill = function(container, liquid) {
- if (liquid == null) {
- liquid = "coffee";
- }
- return "Filling the " + container + " with " + liquid + "...";
- };
转载本站内容时,请务必注明来自W3xue,违者必究。