Coffee的函数

接上篇:CoffeeScript的Sublime Text 2开发环境配置 http://www.cnblogs.com/2gua/archive/2012/07/05/2577603.html

 
一. 定义一个函数
Coffee中定义一个函数,很简单,比如:
#hi.coffee
#定义一个匿名函数,用“->”代表函数定义动作
-> "Hello, 函数!"
#do是运行一个函数
console.log do -> "Hello, 函数!"

 

你用coffee -p hi.coffee试试,输出JavaScript代码,这就是你定义的函数:
(function() {
  (function() {
    return "Hello, 函数!";
  });
 
  console.log((function() {
    return "Hello, 函数!";
  })());
}).call(this);

 -p:打印输出Coffee代码编译成的JavaScript代码,很方便很有用。

 
coffee hi.coffee运行输出:
Hello, 函数!
 
再来定一个复杂点的函数例子:
#hi.coffee
greeting = (var1, var2) -> "Hello, #{var1}, #{var2}!"
console.log greeting '大胖', '小问'

 

coffee -p hi.coffee输出:
(function() {
  var greeting;
 
  greeting = function(var1, var2) {
    return "Hello, " + var1 + ", " + var2 + "!";
  };
 
  console.log(greeting('大胖', '小问'));
}).call(this);

 

coffee hi.coffee运行输出:

Hello, 大胖, 小问!
 
(subject)是参数列表, #{subject}叫作“字符串插值法”。
 
二. arguments对象
JavaScript中的arguments对象,在Coffee中仍能果断使用。
#hi.coffee
greeting = -> "Hello, #{ arguments[0]}, #{ arguments[1]}!"
console.log greeting '大胖', '小问'

 

coffee -p hi.coffee输出:

(function() {
  var greeting;
 
  greeting = function() {
    return "Hello, " + arguments[0] + ", " + arguments[1] + "!";
  };
 
  console.log(greeting('大胖', '小问'));
}).call(this);

 

coffee hi.coffee运行输出:
Hello, 大胖, 小问!
 
额外点出:CoffeeScript中的“is”和“==”都会编译为JavaScript中的“===”。Coffee中摒弃了JavaScript中 “==”。
posted @ 2012-07-08 15:46  2gua  阅读(1644)  评论(1编辑  收藏  举报