# 1語法
### 服務端和客戶端的代碼重用
### 問題
當你在 CoffeeScript 上創建了一個函數,并希望將它用在有網頁瀏覽器的客戶端和有 Node.js 的服務端時。
### 解決方案
以下列方法輸出函數:
~~~
# simpleMath.coffee
?
?
# these methods are private
?
add = (a, b) ->
a + b
?
subtract = (a, b) ->
a - b
?
square = (x) ->
x * x
?
# create a namespace to export our public methods
?
SimpleMath = exports? and exports or @SimpleMath = {}
?
# items attached to our namespace are available in Node.js as well as client browsers
?
class SimpleMath.Calculator
add: add
subtract: subtract
square: square
~~~
### 討論
在上面的例子中,我們創建了一個新的名為 “SimpleMath” 的命名空間。如果 “export” 是有效的,我們的類就會作為一個 Node.js 模塊輸出。如果 “export” 是無效的,那么 “SimpleMath” 就會被加入全局命名空間,這樣就可以被我們的網頁使用了。
在 Node.js 中,我們可以使用 “require” 命令包含我們的模塊。
~~~
$ node
?
> var SimpleMath = require('./simpleMath');
undefined
> var Calc = new SimpleMath.Calculator();
undefined
> console.log("5 + 6 = ", Calc.add(5, 6));
5 + 6 = 11
undefined
>
~~~
在網頁中,我們可以通過將模塊作為一個腳本嵌入其中。
~~~
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>SimpleMath Module Example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="simpleMath.js"></script>
<script>
jQuery(document).ready(function (){
var Calculator = new SimpleMath.Calculator();
var result = $('<li>').html("5 + 6 = " + Calculator.add(5, 6));
$('#SampleResults').append(result);
});
</script>
</head>
<body>
<h1>A SimpleMath Example</h1>
<ul id="SampleResults"></ul>
</body>
</html>
~~~
輸出結果:
**A SimpleMath Example**
**· 5 + 6 = 11**
### 比較范圍
### 問題
如果你想知道某個變量是否在給定的范圍內。
### 解決方案
使用 CoffeeScript 的連綴比較語法。
~~~
maxDwarfism = 147
minAcromegaly = 213
?
height = 180
?
normalHeight = maxDwarfism < height < minAcromegaly
# => true
~~~
### 討論
這是從 Python 中借鑒過來的一個很棒的特性。利用這個特性,不必像下面這樣寫出完整的比較:
~~~
normalHeight = height > maxDwarfism && height < minAcromegaly
~~~
CoffeeScript 支持像寫數學中的比較表達式一樣連綴兩個比較,這樣更直觀。
### 嵌入 JavaScript
### 問題
你想在 CoffeeScript 中嵌入找到的或預先編寫的 JavaScript 代碼。
### 解決方案
把 JavaScript 包裝到撇號中:
~~~
`function greet(name) {
return "Hello "+name;
}`
?
# Back to CoffeeScript
?
greet "Coffee"
# => "Hello Coffee"
~~~
### 討論
這是在 CoffeeScript 代碼中集成少量 JavaScript 而不必用 CoffeeScript 語法轉換它們的最簡單的方法。正如 [CoffeeScript Language Reference](http://jashkenas.github.com/coffee-script/#embedded) 中展示的,可以在一定范圍內混合這兩種語言的代碼:
~~~
hello = `function (name) {
return "Hello "+name
}`
hello "Coffee"
# => "Hello Coffee"
~~~
這里的變量 "hello" 還在 CoffeeScript 中,但賦給它的函數則是用 JavaScript 寫的。
### For 循環
### 問題
你想通過一個 for 循環來迭代數組、對象或范圍。
### 解決方案
~~~
# for(i = 1; i<= 10; i++)
?
x for x in [1..10]
# => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
?
?
# To count by 2
?
# for(i=1; i<= 10; i=i+2)
?
x for x in [1..10] by 2
# => [ 1, 3, 5, 7, 9 ]
?
?
# Perform a simple operation like squaring each item.
?
x * x for x in [1..10]
# = > [1,4,9,16,25,36,49,64,81,100]
~~~
### 討論
CoffeeScript 使用推導(comprehension)來代替 for 循環,這些推導最終會被編譯成 JavaScript 中等價的 for 循環。