GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — coffee-script/index.html at gh-pages · 740521985/coffee-script Expand file tree/ Copy pathindex.htmlMore file actions 3312 lines (2835 loc) · 158 KB / Copy pathindex.htmlFile metadata and controls3312 lines (2835 loc) · 158 KB 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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <meta name="description" content="CoffeeScript 中文, Unfancy JavaScript, 翻译"> <title>CoffeeScript 中文</title> <link rel="canonical" href="http://coffeescript.org" /> <link rel="stylesheet" type="text/css" href="documentation/css/docs.css" /> <link rel="stylesheet" type="text/css" href="documentation/css/tomorrow.css" /> <link rel="shortcut icon" href="documentation/images/favicon.ico" /> </head> <body> <div id="fadeout"></div> <div id="flybar"> <a href="https://github.com/coffee-js/coffee-script"> <img style="position: fixed; top: 0; right: 0; border: 0; z-index: 200;" src="http://coffee-js.qiniudn.com/ribbon.png" alt="Fork me on GitHub"> </a> <a id="logo" href="#top"><img src="documentation/images/logo.png" width="225" height="39" alt="CoffeeScript" /></a> <div class="navigation toc"> <div class="button"> 目录 </div> <div class="contents menu"> <a href="#overview">概览</a> <a href="#installation">安装</a> <a href="#usage">用法</a> <a href="#literate">Literate CoffeeScript</a> <a href="#language">语言手册</a> <a href="#literals">字面量: 函数, 对象和数组</a> <a href="#lexical-scope">词法作用域和变量安全</a> <a href="#conditionals">if, else, unless 和条件赋值</a> <a href="#splats">变参(splats)...</a> <a href="#loops">循环和推导式</a> <a href="#slices">Array Slicing and Splicing</a> <a href="#expressions">Everything is an Expression</a> <a href="#operators">Operators and Aliases</a> <a href="#classes">Classes, Inheritance, and Super</a> <a href="#destructuring">Destructuring Assignment</a> <a href="#fat-arrow">Function Binding</a> <a href="#embedded">Embedded JavaScript</a> <a href="#switch">Switch and Try/Catch</a> <a href="#comparisons">Chained Comparisons</a> <a href="#strings">String Interpolation, Block Strings, and Block Comments</a> <a href="#regexes">Block Regular Expressions</a> <a href="#cake">Cake, and Cakefiles</a> <a href="#source-maps">Source Maps</a> <a href="#scripts">"text/coffeescript" Script Tags</a> <a href="#resources">Books, Screencasts, Examples and Resources</a> <a href="#changelog">Change Log</a> </div> </div> <div class="navigation try"> <div class="button"> 试一试 CoffeeScript <div class="repl_bridge"></div> </div> <div class="contents repl_wrapper"> <div class="code"> <div class="screenshadow tl"></div> <div class="screenshadow tr"></div> <div class="screenshadow bl"></div> <div class="screenshadow br"></div> <div id="repl_source_wrap"> <textarea id="repl_source" rows="100" spellcheck="false">alert "Hello CoffeeScript!"</textarea> </div> <div id="repl_results_wrap"><pre id="repl_results"></pre></div> <div class="minibutton dark run" title="Ctrl-Enter">Run</div> <a class="minibutton permalink" id="repl_permalink">Link</a> <br class="clear" /> </div> </div> </div> <div class="navigation annotated"> <div class="button"> 代码和注释 </div> <div class="contents menu"> <a href="documentation/docs/grammar.html">Grammar Rules — src/grammar</a> <a href="documentation/docs/lexer.html">Lexing Tokens — src/lexer</a> <a href="documentation/docs/rewriter.html">The Rewriter — src/rewriter</a> <a href="documentation/docs/nodes.html">The Syntax Tree — src/nodes</a> <a href="documentation/docs/scope.html">Lexical Scope — src/scope</a> <a href="documentation/docs/helpers.html">Helpers & Utility Functions — src/helpers</a> <a href="documentation/docs/coffee-script.html">The CoffeeScript Module — src/coffee-script</a> <a href="documentation/docs/cake.html">Cake & Cakefiles — src/cake</a> <a href="documentation/docs/command.html">"coffee" Command-Line Utility — src/command</a> <a href="documentation/docs/optparse.html">Option Parsing — src/optparse</a> <a href="documentation/docs/repl.html">Interactive REPL — src/repl</a> <a href="documentation/docs/sourcemap.html">Source Maps — src/sourcemap</a> </div> </div> <div id="error" style="display:none;"></div> </div> <div class="container"> <span class="bookmark" id="top"></span> <p> <b>CoffeeScript 是一门编译到 JavaScript 的小巧语言.</b> 在 Java 般笨拙的外表下, JavaScript 其实有着一颗华丽的心脏. CoffeeScript 尝试用简洁的方式展示 JavaScript 优秀的部分. </p> <p> CoffeeScript 的指导原则是: <b>"她仅仅是 JavaScript"</b>. 代码一一对应地编译到 JS, 不会在编译过程中进行解释. 已有的 JavaScript 类库可以无缝地和 CoffeeScript 搭配使用, 反之亦然. 编译后的代码是可读的, 且经过美化, 能在所有 JavaScript 环境中运行, 并且应该和对应手写的 JavaScript 一样快或者更快. </p> <p> <b>最新版本:</b> <a href="http://github.com/jashkenas/coffee-script/tarball/1.7.1">1.7.1</a> </p> <pre> sudo npm install -g coffee-script</pre> <h2> <span id="overview" class="bookmark"></span> 概览 </h2> <p>左边是 CoffeeScript, 右边是编译后输出的 JavaScript.</p> <div class='code'><pre><code><span class="comment"># 赋值:</span> number = <span class="number">42</span> opposite = <span class="literal">true</span> <span class="comment"># 条件:</span> number = -<span class="number">42</span> <span class="keyword">if</span> opposite <span class="comment"># 函数:</span> <span class="function"><span class="title">square</span> = <span class="params">(x)</span> -></span> x * x <span class="comment"># 数组:</span> list = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>] <span class="comment"># 对象:</span> math = <span class="attribute">root</span>: Math.sqrt <span class="attribute">square</span>: square <span class="attribute">cube</span>: <span class="function"><span class="params">(x)</span> -></span> x * square x <span class="comment"># Splats:</span> <span class="function"><span class="title">race</span> = <span class="params">(winner, runners...)</span> -></span> <span class="built_in">print</span> winner, runners <span class="comment"># 存在性:</span> alert <span class="string">"I knew it!"</span> <span class="keyword">if</span> elvis? <span class="comment"># 数组 推导(comprehensions):</span> cubes = (math.cube num <span class="keyword">for</span> num <span class="keyword">in</span> list) </code></pre><pre><code><span class="keyword">var</span> cubes, list, math, num, number, opposite, race, square, __slice = [].slice; number = <span class="number">42</span>; opposite = <span class="literal">true</span>; <span class="keyword">if</span> (opposite) { number = -<span class="number">42</span>; } square = <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span> <span class="keyword">return</span> x * x; }; list = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>]; math = { root: <span class="built_in">Math</span>.sqrt, square: square, cube: <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span> <span class="keyword">return</span> x * square(x); } }; race = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span> <span class="keyword">var</span> runners, winner; winner = <span class="built_in">arguments</span>[<span class="number">0</span>], runners = <span class="number">2</span> <= <span class="built_in">arguments</span>.length ? __slice.call(<span class="built_in">arguments</span>, <span class="number">1</span>) : []; <span class="keyword">return</span> print(winner, runners); }; <span class="keyword">if</span> (<span class="keyword">typeof</span> elvis !== <span class="string">"undefined"</span> && elvis !== <span class="literal">null</span>) { alert(<span class="string">"I knew it!"</span>); } cubes = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span> <span class="keyword">var</span> _i, _len, _results; _results = []; <span class="keyword">for</span> (_i = <span class="number">0</span>, _len = list.length; _i < _len; _i++) { num = list[_i]; _results.push(math.cube(num)); } <span class="keyword">return</span> _results; })(); </code></pre><script>window.example1 = "# 赋值:\nnumber = 42\nopposite = true\n\n# 条件:\nnumber = -42 if opposite\n\n# 函数:\nsquare = (x) -> x * x\n\n# 数组:\nlist = [1, 2, 3, 4, 5]\n\n# 对象:\nmath =\n root: Math.sqrt\n square: square\n cube: (x) -> x * square x\n\n# Splats:\nrace = (winner, runners...) ->\n print winner, runners\n\n# 存在性:\nalert \"I knew it!\" if elvis?\n\n# 数组 推导(comprehensions):\ncubes = (math.cube num for num in list)\n"</script><div class='minibutton ok' onclick='javascript: var cubes, list, math, num, number, opposite, race, square, __slice = [].slice; number = 42; opposite = true; if (opposite) { number = -42; } square = function(x) { return x * x; }; list = [1, 2, 3, 4, 5]; math = { root: Math.sqrt, square: square, cube: function(x) { return x * square(x); } }; race = function() { var runners, winner; winner = arguments[0], runners = 2 <= arguments.length ? __slice.call(arguments, 1) : []; return print(winner, runners); }; if (typeof elvis !== "undefined" && elvis !== null) { alert("I knew it!"); } cubes = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = list.length; _i < _len; _i++) { num = list[_i]; _results.push(math.cube(num)); } return _results; })(); ;alert(cubes);'>run: cubes</div><br class='clear' /></div> <h2> <span id="installation" class="bookmark"></span> 安装 </h2> <p> CoffeeScript 编译器本身<a href="documentation/docs/grammar.html">是 CoffeeScript 写的</a>, 使用了 <a href="http://jison.org">Jison parser generator</a>. 命令行版本的 <tt>coffee</tt> 是一个实用的 <a href="http://nodejs.org/">Node.js</a> 工具. 不过<a href="extras/coffee-script.js">编译器</a>并不依赖 Node, 而是能运行于任何 JavaScript 执行环境, 比如说在浏览器里(看上边的"试一试 CoffeeScript"). </p> <p> 安装前你需要最新稳定版 <a href="http://nodejs.org/">Node.js</a>, 和 <a href="http://npmjs.org">npm</a> (Node Package Manager). 借助 npm 可以安装 CoffeeScript: </p> <pre> npm install -g coffee-script</pre> <p> (如果不想全局安装可以去掉 <tt>-g</tt> 选项.) </p> <p> 如果你希望安装 <b>master</b> 分支上最新的 CoffeeScript, 你可以从<a href="http://github.com/jashkenas/coffee-script">源码仓库</a> 克隆 CoffeeScript, 或直接下载<a href="http://github.com/jashkenas/coffee-script/tarball/master">源码</a>. 还有通过 npm 方式安装 master 分支最新的 CoffeeScript 编译器: </p> <pre> npm install -g http://github.com/jashkenas/coffee-script/tarball/master</pre> <p> 或者你想将其安装到 <tt>/usr/local</tt>, 而不用 npm 进行管理, 进入 <tt>coffee-script</tt> 目录执行: </p> <pre> sudo bin/cake install</pre> <h2> <span id="usage" class="bookmark"></span> 用法 </h2> <p> 安装之后, 你应该可以运行 <tt>coffee</tt> 命令以执行脚本, 编译 <tt>.coffee</tt> 文件到 <tt>.js</tt> 文件, 和提供一个交互式的 REPL. <tt>coffee</tt> 命令有下列参数: </p> <table> <tr> <td><code>-c, --compile</code></td> <td> 编译一个 <tt>.coffee</tt> 脚本到一个同名的 <tt>.js</tt> 文件. </td> </tr> <tr> <td><code>-m, --map</code></td> <td> 随 JavaScript 文件一起生成 source maps. 并且在 JavaScript 里加上 <tt>sourceMappingURL</tt> 指令. </td> </tr> <tr> <td width="25%"><code>-i, --interactive</code></td> <td> 启动一个交互式的 CoffeeScript 会话用来尝试一些代码片段. 等同于执行 <tt>coffee</tt> 而不加参数. </td> </tr> <tr> <td><code>-o, --output [DIR]</code></td> <td> 将所有编译后的 JavaScript 文件写到指定文件夹. 与 <tt>--compile</tt> 或 <tt>--watch</tt> 搭配使用. </td> </tr> <tr> <td><code>-j, --join [FILE]</code></td> <td> 编译之前, 按参数传入顺序连接所有脚本到一起, 编译后写到指定的文件. 对于编译大型项目有用. </td> </tr> <tr> <td><code>-w, --watch</code></td> <td> 监视文件改变, 任何文件更新时重新执行命令. </td> </tr> <tr> <td><code>-p, --print</code></td> <td> JavaScript 直接打印到 <b>stdout</b> 而不是写到一个文件. </td> </tr> <tr> <td><code>-s, --stdio</code></td> <td> 将 CoffeeScript 传递到 STDIN 后从 STDOUT 获取 JavaScript. 对其他语言写的进程有好处. 比如:<br /> <tt>cat src/cake.coffee | coffee -sc</tt> </td> </tr> <tr> <td><code>-l, --literate</code></td> <td> 将代码作为 Literate CoffeeScript 解析. 只会在从 <b>stdio</b> 直接传入代码或者处理某些没有后缀的文件名需要写明这点. </td> </tr> <tr> <td><code>-e, --eval</code></td> <td> 直接从命令行编译和打印一小段 CoffeeScript. 比如:<br /> <tt>coffee -e "console.log num for num in [10..1]"</tt> </td> </tr> <tr> <td><code>-b, --bare</code></td> <td> 编译到 JavaScript 时去掉<a href="#lexical-scope">顶层函数的包裹</a>. </td> </tr> <tr> <td><code>-t, --tokens</code></td> <td> 不对 CoffeeScript 进行解析, 仅仅进行 lex, 打印出 token stream: <tt>[IDENTIFIER square] [ASSIGN =] [PARAM_START (]</tt> ... </td> </tr> <tr> <td><code>-n, --nodes</code></td> <td> 不对 CoffeeScript 进行编译, 仅仅 lex 和解析, 打印 parse tree: <pre class="no_bar"> Expressions Assign Value "square" Code "x" Op * Value "x" Value "x"</pre> </td> </tr> <tr> <td><code>--nodejs</code></td> <td> <tt>node</tt> 命令有一些实用的参数, 比如<br /> <tt>--debug</tt>, <tt>--debug-brk</tt>, <tt>--max-stack-size</tt>, 和 <tt>--expose-gc</tt>. 用这个参数直接把参数转发到 Node.js. 重复使用 <tt>--nodejs</tt> 来传递多个参数. </td> </tr> </table> <p> <b>例子:</b> </p> <ul> <li> 编译一个 <tt>.coffee</tt> 文件的树形目录 <tt>src</tt> 到一个同级 <tt>.js</tt> 文件树形目录 <tt>lib</tt>:<br /> <tt>coffee --compile --output lib/ src/</tt> </li> <li> 监视一个文件的改变, 每次文件被保证时重新编译:<br /> <tt>coffee --watch --compile experimental.coffee</tt> </li> <li> 合并一组文件到单个脚本:<br /> <tt>coffee --join project.js --compile src/*.coffee</tt> </li> <li> 从一个 one-liner 打印编译后的 JS:<br /> <tt>coffee -bpe "alert i for i in [0..10]"</tt> </li> <li> 现在全部一起, 在你工作时监视和重复编译整个项目:<br /> <tt>coffee -o lib/ -cw src/</tt> </li> <li> 运行 CoffeeScript REPL (<tt>Ctrl-D</tt> 来终止, <tt>Ctrl-V</tt> 激活多行):<br /> <tt>coffee</tt> </li> </ul> <h2> <span id="literate" class="bookmark"></span> Literate CoffeeScript </h2> <p> 除了被作为一个普通的编程语言, CoffeeScript 也可以在 "literate" 模式下编写。 如果你以 <tt>.litcoffee</tt> 为扩展名命名你的文件, 你可以把它当作 Markdown 文件来编写 — 此文档恰好也是一份可执行的 CoffeeScript 代码, 编译器将会把所有的缩进块 (Markdown 表示源代码的方式) 视为代码, 其他部分则为注释. </p> <p> Just for kicks, a little bit of the compiler is currently implemented in this fashion: See it <a href="https://gist.github.com/jashkenas/3fc3c1a8b1009c00d9df">as a document</a>, <a href="https://raw.github.com/jashkenas/coffee-script/master/src/scope.litcoffee">raw</a>, and <a href="http://cl.ly/LxEu">properly highlighted in a text editor</a>. </p> <p> I'm fairly excited about this direction for the language, and am looking forward to writing (and more importantly, reading) more programs in this style. More information about Literate CoffeeScript, including an <a href="https://github.com/jashkenas/journo">example program</a>, are <a href="http://ashkenas.com/literate-coffeescript">available in this blog post</a>. </p> <h2> <span id="language" class="bookmark"></span> 语言手册 </h2> <p> <i> 这份手册所设计的结构, 方便从上往下进行阅读. 后边的章节使用前面介绍的语法和手法. 阅读这份手册需要对 JavaScript 比较熟悉. 以下所有的例子, CoffeeScript 源码将在左边显示, 并在右侧直接编译到 JavaScript. </i> </p> <p> <i> 很多例子可以通过点击右边的 <b>run</b> 按钮直接运行(代码有意义的话), 也可以通过点击左边的 <b>load</b> 按钮载入"试一试 CoffeeScript"的控制台. </i> <p> 首先, 一些基础, CoffeeScript 使用显式的空白来区分代码块. 你不需要使用分号 <tt>;</tt> 来关闭表达式, 在一行的结尾换行就可以了(尽管分号依然可以用来把多行的表达式简写到一行里). 不需要再用花括号来 <tt>{ }</tt> 包裹代码快, 在 <a href="#literals">函数</a>, <a href="#conditionals">if 表达式</a>, <a href="#switch">switch</a>, 和 <a href="#try">try/catch</a> 当中使用缩进. </p> <p> 传入参数的时候, 你不需要再使用圆括号来表明函数被执行. 隐式的函数调用的作用范围一直到行尾或者一个块级表达式. <br /> <tt>console.log sys.inspect object</tt> → <tt>console.log(sys.inspect(object));</tt> </p> <p> <span id="literals" class="bookmark"></span> <b class="header">函数</b> 函数通过一组可选的圆括号包裹的参数, 一个箭头, 一个函数体来定义. 一个空的函数像是这样: <tt>-></tt> </p> <div class='code'><pre><code><span class="function"><span class="title">square</span> = <span class="params">(x)</span> -></span> x * x <span class="function"><span class="title">cube</span> = <span class="params">(x)</span> -></span> square(x) * x </code></pre><pre><code><span class="keyword">var</span> cube, square; square = <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span> <span class="keyword">return</span> x * x; }; cube = <span class="function"><span class="keyword">function</span><span class="params">(x)</span> {</span> <span class="keyword">return</span> square(x) * x; }; </code></pre><script>window.example2 = "square = (x) -> x * x\ncube = (x) -> square(x) * x\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example2);'>load</div><div class='minibutton ok' onclick='javascript: var cube, square; square = function(x) { return x * x; }; cube = function(x) { return square(x) * x; }; ;alert(cube(5));'>run: cube(5)</div><br class='clear' /></div> <p> 一些函数函数参数会有默认值, 当传入的参数的不存在 (<tt>null</tt> 或者 <tt>undefined</tt>) 时会被使用. </p> <div class='code'><pre><code><span class="function"><span class="title">fill</span> = <span class="params">(container, liquid = <span class="string">"coffee"</span>)</span> -></span> <span class="string">"Filling the <span class="subst">#{container}</span> with <span class="subst">#{liquid}</span>..."</span> </code></pre><pre><code><span class="keyword">var</span> fill; fill = <span class="function"><span class="keyword">function</span><span class="params">(container, liquid)</span> {</span> <span class="keyword">if</span> (liquid == <span class="literal">null</span>) { liquid = <span class="string">"coffee"</span>; } <span class="keyword">return</span> <span class="string">"Filling the "</span> + container + <span class="string">" with "</span> + liquid + <span class="string">"..."</span>; }; </code></pre><script>window.example3 = "fill = (container, liquid = \"coffee\") ->\n \"Filling the #{container} with #{liquid}...\"\n\n\n\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example3);'>load</div><div class='minibutton ok' onclick='javascript: var fill; fill = function(container, liquid) { if (liquid == null) { liquid = "coffee"; } return "Filling the " + container + " with " + liquid + "..."; }; ;alert(fill("cup"));'>run: fill("cup")</div><br class='clear' /></div> <p> <span id="objects_and_arrays" class="bookmark"></span> <b class="header">对象和数组</b> CoffeeScript 中对象和数组的字面量看起来很像在 JavaScript 中的写法. 如果单个属性被写在自己的一行里, 那么逗号是可以省略的. 和 <a href="http://yaml.org">YAML</a> 类似, 对象可以用缩进替代花括号来声明. </p> <div class='code'><pre><code>song = [<span class="string">"do"</span>, <span class="string">"re"</span>, <span class="string">"mi"</span>, <span class="string">"fa"</span>, <span class="string">"so"</span>] singers = {<span class="attribute">Jagger</span>: <span class="string">"Rock"</span>, <span class="attribute">Elvis</span>: <span class="string">"Roll"</span>} bitlist = [ <span class="number">1</span>, <span class="number">0</span>, <span class="number">1</span> <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span> <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span> ] kids = <span class="attribute">brother</span>: <span class="attribute">name</span>: <span class="string">"Max"</span> <span class="attribute">age</span>: <span class="number">11</span> <span class="attribute">sister</span>: <span class="attribute">name</span>: <span class="string">"Ida"</span> <span class="attribute">age</span>: <span class="number">9</span> </code></pre><pre><code><span class="keyword">var</span> bitlist, kids, singers, song; song = [<span class="string">"do"</span>, <span class="string">"re"</span>, <span class="string">"mi"</span>, <span class="string">"fa"</span>, <span class="string">"so"</span>]; singers = { Jagger: <span class="string">"Rock"</span>, Elvis: <span class="string">"Roll"</span> }; bitlist = [<span class="number">1</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>]; kids = { brother: { name: <span class="string">"Max"</span>, age: <span class="number">11</span> }, sister: { name: <span class="string">"Ida"</span>, age: <span class="number">9</span> } }; </code></pre><script>window.example4 = "song = [\"do\", \"re\", \"mi\", \"fa\", \"so\"]\n\nsingers = {Jagger: \"Rock\", Elvis: \"Roll\"}\n\nbitlist = [\n 1, 0, 1\n 0, 0, 1\n 1, 1, 0\n]\n\nkids =\n brother:\n name: \"Max\"\n age: 11\n sister:\n name: \"Ida\"\n age: 9\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example4);'>load</div><div class='minibutton ok' onclick='javascript: var bitlist, kids, singers, song; song = ["do", "re", "mi", "fa", "so"]; singers = { Jagger: "Rock", Elvis: "Roll" }; bitlist = [1, 0, 1, 0, 0, 1, 1, 1, 0]; kids = { brother: { name: "Max", age: 11 }, sister: { name: "Ida", age: 9 } }; ;alert(song.join(" ... "));'>run: song.join(" ... ")</div><br class='clear' /></div> <p> JavaScript 里, 你不能使用不添加引号的保留字段作为属性名称, 比如 <tt>class</tt>. CoffeeScript 里作为键出现的保留字会被识别并补上引号, 所以你不用有额外的操心(比如说, 使用 jQuery 的时候). </p> <div class='code'><pre><code>$('.account').attr class: 'active' log object.class </code></pre><pre><code>$(<span class="string">'.account'</span>).attr({ <span class="string">"class"</span>: <span class="string">'active'</span> }); log(object[<span class="string">"class"</span>]); </code></pre><script>window.example5 = "$('.account').attr class: 'active'\n\nlog object.class\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example5);'>load</div><br class='clear' /></div> <p> <span id="lexical-scope" class="bookmark"></span> <b class="header">词法作用域和变量安全</b> CoffeeScript 编译器会考虑所有变量, 保证每个变量都在词法域里适当地被定义 — 你永远不需要自己去写 <tt>var</tt>. </p> <div class='code'><pre><code>outer = <span class="number">1</span> <span class="function"><span class="title">changeNumbers</span> = -></span> inner = -<span class="number">1</span> outer = <span class="number">10</span> inner = changeNumbers()</code></pre><pre><code><span class="keyword">var</span> changeNumbers, inner, outer; outer = <span class="number">1</span>; changeNumbers = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span> <span class="keyword">var</span> inner; inner = -<span class="number">1</span>; <span class="keyword">return</span> outer = <span class="number">10</span>; }; inner = changeNumbers(); </code></pre><script>window.example6 = "outer = 1\nchangeNumbers = ->\n inner = -1\n outer = 10\ninner = changeNumbers()"</script><div class='minibutton load' onclick='javascript: loadConsole(example6);'>load</div><div class='minibutton ok' onclick='javascript: var changeNumbers, inner, outer; outer = 1; changeNumbers = function() { var inner; inner = -1; return outer = 10; }; inner = changeNumbers(); ;alert(inner);'>run: inner</div><br class='clear' /></div> <p> 注意所有变量的定义都被推到相关的顶层作用域, 也就是第一次出现的位置. <b>outer</b> 在内层的函数里没有被重新定义, 因为它已经存在于作用域当中了. 同时, 内层函数里的 <b>inner</b> 不应该改变外部的同名的变量, 所以在这里有自己的声明. </p> <p> 其行为和 Ruby 的局部变量的作用域实际上是一致的. 由于你没有对 <tt>var</tt> 关键字的直接访问, 根据需要隐藏一个外部变量就很容易, 你只能引用它. 所以在写深层的嵌套的函数时, 注意不要意外用到和外部变量相同的名字. </p> <p> 尽管要说清楚会受到文档长度限制, 函数的所有 CoffeeScript 结果都被一个匿名函数包裹: <tt>(function(){ ... })();</tt> 这层安全的封装, 加上自动生成的 <tt>var</tt> 关键字, 使得不小心污染全局命名空间很难发生. </p> <p> 如果你希望创建一个其他脚本也能使用的顶层变量, 那么将其作为赋值在 <b>window</b> 上, 或者在 CommonJS 里的 <b>exports</b> 上. <b>存在操作符(existential operator)</b>可以帮你写出一个可靠的方式找到添加位置; 比如你的目标是同时满足 CommonJS 和浏览器: <tt>exports ? this</tt> </p> <p> <span id="conditionals" class="bookmark"></span> <b class="header">if, else, unless 和条件赋值</b> <b>if/else</b> 表达式可以不用圆括号和花括号就写出来. 就像函数和其他块级表达式那样, 多行的条件可以通过缩进来表明. 另外还有一个顺手的后缀形式, 在行尾使用 <tt>if</tt> or <tt>unless</tt>. </p> <p> CoffeeScript 会尝试编译 <b>if</b> 语句到 JavaScript 表达式, 或者一个封装的闭包. CoffeeScript 里不存在直白的三元表达式. — 你只要在一行内使用普通的 <b>if</b> 语句. </p> <div class='code'><pre><code>mood = greatlyImproved <span class="keyword">if</span> singing <span class="keyword">if</span> happy <span class="keyword">and</span> knowsIt clapsHands() chaChaCha() <span class="keyword">else</span> showIt() date = <span class="keyword">if</span> friday <span class="keyword">then</span> sue <span class="keyword">else</span> jill </code></pre><pre><code><span class="keyword">var</span> date, mood; <span class="keyword">if</span> (singing) { mood = greatlyImproved; } <span class="keyword">if</span> (happy && knowsIt) { clapsHands(); chaChaCha(); } <span class="keyword">else</span> { showIt(); } date = friday ? sue : jill; </code></pre><script>window.example7 = "mood = greatlyImproved if singing\n\nif happy and knowsIt\n clapsHands()\n chaChaCha()\nelse\n showIt()\n\ndate = if friday then sue else jill\n\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example7);'>load</div><br class='clear' /></div> <p> <span id="splats" class="bookmark"></span> <b class="header">变参(splats)...</b> 使用 JavaScript 的 <b>arguments 对象</b>是一种处理接收不定数量个参数的函数常用办法. CoffeeScript 在函数定义和调用里提供了变参(splats) <tt>...</tt> 的语法, 让不定个数的参数使用起来更愉悦一些. </p> <div class='code'><pre><code>gold = silver = rest = <span class="string">"unknown"</span> <span class="function"><span class="title">awardMedals</span> = <span class="params">(first, second, others...)</span> -></span> gold = first silver = second rest = others contenders = [ <span class="string">"Michael Phelps"</span> <span class="string">"Liu Xiang"</span> <span class="string">"Yao Ming"</span> <span class="string">"Allyson Felix"</span> <span class="string">"Shawn Johnson"</span> <span class="string">"Roman Sebrle"</span> <span class="string">"Guo Jingjing"</span> <span class="string">"Tyson Gay"</span> <span class="string">"Asafa Powell"</span> <span class="string">"Usain Bolt"</span> ] awardMedals contenders... alert <span class="string">"Gold: "</span> + gold alert <span class="string">"Silver: "</span> + silver alert <span class="string">"The Field: "</span> + rest </code></pre><pre><code><span class="keyword">var</span> awardMedals, contenders, gold, rest, silver, __slice = [].slice; gold = silver = rest = <span class="string">"unknown"</span>; awardMedals = <span class="function"><span class="keyword">function</span><span class="params">()</span> {</span> <span class="keyword">var</span> first, others, second; first = <span class="built_in">arguments</span>[<span class="number">0</span>], second = <span class="built_in">arguments</span>[<span class="number">1</span>], others = <span class="number">3</span> <= <span class="built_in">arguments</span>.length ? __slice.call(<span class="built_in">arguments</span>, <span class="number">2</span>) : []; gold = first; silver = second; <span class="keyword">return</span> rest = others; }; contenders = [<span class="string">"Michael Phelps"</span>, <span class="string">"Liu Xiang"</span>, <span class="string">"Yao Ming"</span>, <span class="string">"Allyson Felix"</span>, <span class="string">"Shawn Johnson"</span>, <span class="string">"Roman Sebrle"</span>, <span class="string">"Guo Jingjing"</span>, <span class="string">"Tyson Gay"</span>, <span class="string">"Asafa Powell"</span>, <span class="string">"Usain Bolt"</span>]; awardMedals.apply(<span class="literal">null</span>, contenders); alert(<span class="string">"Gold: "</span> + gold); alert(<span class="string">"Silver: "</span> + silver); alert(<span class="string">"The Field: "</span> + rest); </code></pre><script>window.example8 = "gold = silver = rest = \"unknown\"\n\nawardMedals = (first, second, others...) ->\n gold = first\n silver = second\n rest = others\n\ncontenders = [\n \"Michael Phelps\"\n \"Liu Xiang\"\n \"Yao Ming\"\n \"Allyson Felix\"\n \"Shawn Johnson\"\n \"Roman Sebrle\"\n \"Guo Jingjing\"\n \"Tyson Gay\"\n \"Asafa Powell\"\n \"Usain Bolt\"\n]\n\nawardMedals contenders...\n\nalert \"Gold: \" + gold\nalert \"Silver: \" + silver\nalert \"The Field: \" + rest\n\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example8);'>load</div><div class='minibutton ok' onclick='javascript: var awardMedals, contenders, gold, rest, silver, __slice = [].slice; gold = silver = rest = "unknown"; awardMedals = function() { var first, others, second; first = arguments[0], second = arguments[1], others = 3 <= arguments.length ? __slice.call(arguments, 2) : []; gold = first; silver = second; return rest = others; }; contenders = ["Michael Phelps", "Liu Xiang", "Yao Ming", "Allyson Felix", "Shawn Johnson", "Roman Sebrle", "Guo Jingjing", "Tyson Gay", "Asafa Powell", "Usain Bolt"]; awardMedals.apply(null, contenders); alert("Gold: " + gold); alert("Silver: " + silver); alert("The Field: " + rest); ;'>run</div><br class='clear' /></div> <p> <span id="loops" class="bookmark"></span> <b class="header">循环和推导式</b> 你可以使用CoffeeScript将大多数的循环写成基于数组、对象或范围的推导式(comprehensions)。 推导式替代(编译为)<b>for</b>循环,并且可以使用可选的子句和数组索引值。 不同于<b>for</b>循环,数组的推导式是表达式,可以被返回和赋值。 </p> <div class='code'><pre><code><span class="comment"># 吃午饭.</span> eat food <span class="keyword">for</span> food <span class="keyword">in</span> [<span class="string">'toast'</span>, <span class="string">'cheese'</span>, <span class="string">'wine'</span>] <span class="comment"># 精致的五道菜.</span> courses = [<span class="string">'greens'</span>, <span class="string">'caviar'</span>, <span class="string">'truffles'</span>, <span class="string">'roast'</span>, <span class="string">'cake'</span>] menu i + <span class="number">1</span>, dish <span class="keyword">for</span> dish, i <span class="keyword">in</span> courses <span class="comment"># 注重健康的一餐.</span> foods = [<span class="string">'broccoli'</span>, <span class="string">'spinach'</span>, <span class="string">'chocolate'</span>] eat food <span class="keyword">for</span> food <span class="keyword">in</span> foods <span class="keyword">when</span> food <span class="keyword">isnt</span> <span class="string">'chocolate'</span> </code></pre><pre><code><span class="keyword">var</span> courses, dish, food, foods, i, _i, _j, _k, _len, _len1, _len2, _ref; _ref = [<span class="string">'toast'</span>, <span class="string">'cheese'</span>, <span class="string">'wine'</span>]; <span class="keyword">for</span> (_i = <span class="number">0</span>, _len = _ref.length; _i < _len; _i++) { food = _ref[_i]; eat(food); } courses = [<span class="string">'greens'</span>, <span class="string">'caviar'</span>, <span class="string">'truffles'</span>, <span class="string">'roast'</span>, <span class="string">'cake'</span>]; <span class="keyword">for</span> (i = _j = <span class="number">0</span>, _len1 = courses.length; _j < _len1; i = ++_j) { dish = courses[i]; menu(i + <span class="number">1</span>, dish); } foods = [<span class="string">'broccoli'</span>, <span class="string">'spinach'</span>, <span class="string">'chocolate'</span>]; <span class="keyword">for</span> (_k = <span class="number">0</span>, _len2 = foods.length; _k < _len2; _k++) { food = foods[_k]; <span class="keyword">if</span> (food !== <span class="string">'chocolate'</span>) { eat(food); } } </code></pre><script>window.example9 = "# 吃午饭.\neat food for food in ['toast', 'cheese', 'wine']\n\n# 精致的五道菜.\ncourses = ['greens', 'caviar', 'truffles', 'roast', 'cake']\nmenu i + 1, dish for dish, i in courses\n\n# 注重健康的一餐.\nfoods = ['broccoli', 'spinach', 'chocolate']\neat food for food in foods when food isnt 'chocolate'\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example9);'>load</div><br class='clear' /></div> <p> 推导式可以适用于其他一些使用循环的地方,例如<b>each</b>/<b>forEach</b>, <b>map</b>,或者<b>select</b>/<b>filter</b>,例如: <tt>shortNames = (name for name in list when name.length < 5)</tt><br /> 如果你知道循环的开始与结束,或者希望以固定的跨度迭代,你可以在范围推导式中 指定开始与结束。 </p> <div class='code'><pre><code>countdown = (num <span class="keyword">for</span> num <span class="keyword">in</span> [<span class="number">10.</span><span class="number">.1</span>]) </code></pre><pre><code><span class="keyword">var</span> countdown, num; countdown = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span> <span class="keyword">var</span> _i, _results; _results = []; <span class="keyword">for</span> (num = _i = <span class="number">10</span>; _i >= <span class="number">1</span>; num = --_i) { _results.push(num); } <span class="keyword">return</span> _results; })(); </code></pre><script>window.example10 = "countdown = (num for num in [10..1])\n\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example10);'>load</div><div class='minibutton ok' onclick='javascript: var countdown, num; countdown = (function() { var _i, _results; _results = []; for (num = _i = 10; _i >= 1; num = --_i) { _results.push(num); } return _results; })(); ;alert(countdown);'>run: countdown</div><br class='clear' /></div> <p> 注意:上面的例子中我们展示了如何将推导式赋值给变量,CoffeeScript总是将 每个循环项收集到一个数组中。但是有时候以循环结尾的函数运行的目的就是 它们的副作用(side-effects)。这种情况下要注意不要意外的返回推导式的结果, 而是在函数的结尾增加一些有意义的返回值—例如<tt>true</tt> — 或 <tt>null</tt>。 </p> <p> 在推导式中使用<tt>by</tt>子句,可以实现以固定跨度迭代范围值: <tt>evens = (x for x in [0..10] by 2)</tt> </p> <p> 推导式也可以用于迭代对象中的key和value。在推导式中使用<tt>of</tt> 来取出对象中的属性,而不是数组中的值。 </p> <div class='code'><pre><code>yearsOld = <span class="attribute">max</span>: <span class="number">10</span>, <span class="attribute">ida</span>: <span class="number">9</span>, <span class="attribute">tim</span>: <span class="number">11</span> ages = <span class="keyword">for</span> child, age <span class="keyword">of</span> yearsOld <span class="string">"<span class="subst">#{child}</span> is <span class="subst">#{age}</span>"</span> </code></pre><pre><code><span class="keyword">var</span> age, ages, child, yearsOld; yearsOld = { max: <span class="number">10</span>, ida: <span class="number">9</span>, tim: <span class="number">11</span> }; ages = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span> <span class="keyword">var</span> _results; _results = []; <span class="keyword">for</span> (child <span class="keyword">in</span> yearsOld) { age = yearsOld[child]; _results.push(<span class="string">""</span> + child + <span class="string">" is "</span> + age); } <span class="keyword">return</span> _results; })(); </code></pre><script>window.example11 = "yearsOld = max: 10, ida: 9, tim: 11\n\nages = for child, age of yearsOld\n \"#{child} is #{age}\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example11);'>load</div><div class='minibutton ok' onclick='javascript: var age, ages, child, yearsOld; yearsOld = { max: 10, ida: 9, tim: 11 }; ages = (function() { var _results; _results = []; for (child in yearsOld) { age = yearsOld[child]; _results.push("" + child + " is " + age); } return _results; })(); ;alert(ages.join(", "));'>run: ages.join(", ")</div><br class='clear' /></div> <p> 如果你希望仅迭代在当前对象中定义的属性,通过<tt>hasOwnProperty</tt>检查并 避免属性是继承来的,可以这样来写:<br /> <tt>for own key, value of object</tt> </p> <p> CoffeeScript仅提供了一种底层循环,即<b>while</b>循环。与JavaScript中的<b>while</b> 循环的主要区别是,在CoffeeScript中<b>while</b>可以作为表达式来使用, 而且可以返回一个数组,该数组包含每个迭代项的迭代结果。 </p> <div class='code'><pre><code><span class="comment"># 经济 101</span> <span class="keyword">if</span> <span class="keyword">this</span>.studyingEconomics buy() <span class="keyword">while</span> supply > demand sell() <span class="keyword">until</span> supply > demand <span class="comment"># 摇篮曲</span> num = <span class="number">6</span> lyrics = <span class="keyword">while</span> num -= <span class="number">1</span> <span class="string">"<span class="subst">#{num}</span> little monkeys, jumping on the bed. One fell out and bumped his head."</span> </code></pre><pre><code><span class="keyword">var</span> lyrics, num; <span class="keyword">if</span> (<span class="keyword">this</span>.studyingEconomics) { <span class="keyword">while</span> (supply > demand) { buy(); } <span class="keyword">while</span> (!(supply > demand)) { sell(); } } num = <span class="number">6</span>; lyrics = (<span class="function"><span class="keyword">function</span><span class="params">()</span> {</span> <span class="keyword">var</span> _results; _results = []; <span class="keyword">while</span> (num -= <span class="number">1</span>) { _results.push(<span class="string">""</span> + num + <span class="string">" little monkeys, jumping on the bed. One fell out and bumped his head."</span>); } <span class="keyword">return</span> _results; })(); </code></pre><script>window.example12 = "# 经济 101\nif this.studyingEconomics\n buy() while supply > demand\n sell() until supply > demand\n\n# 摇篮曲\nnum = 6\nlyrics = while num -= 1\n \"#{num} little monkeys, jumping on the bed.\n One fell out and bumped his head.\"\n"</script><div class='minibutton load' onclick='javascript: loadConsole(example12);'>load</div><div class='minibutton ok' onclick='javascript: var lyrics, num; if (this.studyingEconomics) { while (supply > demand) { buy(); } while (!(supply > demand)) { sell(); } } num = 6; |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |