暴走编程

Just Do IT

学习 Coffee-script 及环境安装 (Mac)

Keyword

Homebrew: http://mxcl.github.io/homebrew/index_zh-cn.html

V8: https://code.google.com/p/v8/

NodeJS: http://nodejs.org/

Coffee: http://coffeescript.org/

npm: https://npmjs.org/

环境安装(OS X)

首先确保 Homebrew 安装了, <div class=’bogus-wrapper’>

<figcaption></figcaption><div class=”highlight”><table><tr><td class=”gutter”><pre class=”line-numbers”>1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 </pre></td><td class=’code’><pre>$ brew --version 0.9.4 $ brew update # 安装 NodeJS $ brew install nodejs # 如果之前安装过旧版本的 NodeJS,升级到当前最新版本 $ brew upgrade nodejs $ node --version v0.10.5 $ npm --version 1.2.18 # 安装 Coffee $ npm install -g coffee-script npm http GET https://registry.npmjs.org/coffee-script npm http 200 https://registry.npmjs.org/coffee-script npm http GET https://registry.npmjs.org/coffee-script/-/coffee-script-1.6.2.tgz npm http 200 https://registry.npmjs.org/coffee-script/-/coffee-script-1.6.2.tgz /usr/local/share/npm/bin/coffee -> /usr/local/share/npm/lib/node_modules/coffee-script/bin/coffee /usr/local/share/npm/bin/cake -> /usr/local/share/npm/lib/node_modules/coffee-script/bin/cake $ /usr/local/share/npm/bin/coffee --version CoffeeScript version 1.6.2 # 安装 V8 JavaScript Engine,用于在 terminal 中运行 Javascript 并输出运行结果 $ brew install v8 $ v8 V8 version 3.18.2 [sample shell] > print(1+1) 2 > </pre></td></tr></table></div>
</div>

编写一个 Coffee 脚本

example_01.js.coffee
1
2
3
square = (x) -> x * x
cube = (x) -> square(x) * x
print cube(5)

将 Coffee 编译成 Javascript:

1
$ /usr/local/share/npm/bin/coffee -c example_01.js.coffee

编译后对应生成的 Javascript 文件 <div class=’bogus-wrapper’>

<figcaption></figcaption><div class=”highlight”><table><tr><td class=”gutter”><pre class=”line-numbers”>1 2 </pre></td><td class=’code’><pre>$ ls example_01.js.coffee example_01.js.js </pre></td></tr></table></div>
</div>

example_01.js.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Generated by CoffeeScript 1.6.2
(function() {
  var cube, square;

  square = function(x) {
    return x * x;
  };

  cube = function(x) {
    return square(x) * x;
  };

  print(cube(5));

}).call(this);

运行 example_01.js.js <div class=’bogus-wrapper’>

<figcaption></figcaption><div class=”highlight”><table><tr><td class=”gutter”><pre class=”line-numbers”>1 2 </pre></td><td class=’code’><pre>$ v8 example_01.js.js 125 </pre></td></tr></table></div>
</div>

使用体会

简而言之,Coffee 的语法有点像 Ruby,数组的语法又是 yaml,对与熟悉 Rails 写过 Ruby 的很容易上手,反之,对于新手,因继承了 Ruby 的一些优点,学习来也容易理解,加上很人性的官方文档,学习的过程中可以说是一种享受,这里可能需要注意的是,如果之前没有接触过动态类型的语言,比如从事的语言 Java 比较多,可能会受些干扰,其实他们之前没有什么必然联系。如果是 C Sharp 可能稍微好些,用过 Linq 的应该有体会,包括从 C Sharp 4.0 之后加入了一些动态语言的特性.

Comments