mirror of
https://github.com/jashkenas/coffeescript.git
synced 2022-11-09 12:23:24 -05:00
Updated v2 docs generated output
This commit is contained in:
parent
3379f233e8
commit
5d557a54e1
1 changed files with 209 additions and 152 deletions
|
|
@ -51,6 +51,15 @@ a:focus, a:hover, a:active {
|
|||
background-color: #3e2723 !important;
|
||||
}
|
||||
|
||||
.bg-ribbed-light {
|
||||
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 3"><path opacity=".03" fill="#000" d="M0 0h1v1H0z"/><path opacity=".005" fill="#000" d="M0 1h1v2H0z"/></svg>');
|
||||
background-size: 1px 3px;
|
||||
}
|
||||
.bg-ribbed-dark {
|
||||
background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1 3"><path opacity=".2" fill="#000" d="M0 0h1v1H0z"/><path opacity=".15" fill="#000" d="M0 1h1v2H0z"/></svg>');
|
||||
background-size: 1px 3px;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* Header
|
||||
|
|
@ -149,7 +158,7 @@ a:focus, a:hover, a:active {
|
|||
|
||||
.sidebar {
|
||||
background-color: #efebe9;
|
||||
border-right: 1px solid #eee;
|
||||
border-right: 1px solid #efebe9;
|
||||
top: 3.5rem;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
|
|
@ -264,6 +273,10 @@ a:focus, a:hover, a:active {
|
|||
font-size: 1.3rem;
|
||||
font-weight: 300;
|
||||
}
|
||||
.main td {
|
||||
vertical-align: top;
|
||||
padding: 0.3em 0;
|
||||
}
|
||||
.main strong, .main th {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
|
@ -404,7 +417,7 @@ textarea {
|
|||
</head>
|
||||
<body>
|
||||
|
||||
<nav class="navbar navbar-dark navbar-fixed-top bg-inverse">
|
||||
<nav class="navbar navbar-dark navbar-fixed-top bg-inverse bg-ribbed-dark">
|
||||
<a class="navbar-brand" href="#"><svg xmlns="http://www.w3.org/2000/svg" viewBox="-22 347 566 100">
|
||||
<title>
|
||||
CoffeeScript Logo
|
||||
|
|
@ -431,7 +444,7 @@ textarea {
|
|||
|
||||
<div class="container-fluid" id="top">
|
||||
<div class="row row-offcanvas row-offcanvas-left">
|
||||
<nav class="sidebar sidebar-offcanvas col-xs-12 col-lg-3">
|
||||
<nav class="sidebar sidebar-offcanvas col-xs-12 col-lg-3 bg-ribbed-light">
|
||||
<nav class="contents" id="contents">
|
||||
<ul class="nav">
|
||||
<li class="nav-item">
|
||||
|
|
@ -492,10 +505,7 @@ textarea {
|
|||
<a href="#destructuring" class="nav-link" data-action="sidebar-nav">Destructuring Assignment</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="#fat-arrow" class="nav-link" data-action="sidebar-nav">Bound and Generator Functions</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="#embedded" class="nav-link" data-action="sidebar-nav">Embedded JavaScript</a>
|
||||
<a href="#fat-arrow" class="nav-link" data-action="sidebar-nav">Function Modifiers</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="#switch" class="nav-link" data-action="sidebar-nav">Switch and Try/Catch</a>
|
||||
|
|
@ -512,6 +522,9 @@ textarea {
|
|||
<li class="nav-item">
|
||||
<a href="#modules" class="nav-link" data-action="sidebar-nav">Modules</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="#embedded" class="nav-link" data-action="sidebar-nav">Embedded JavaScript</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
|
|
@ -533,19 +546,19 @@ textarea {
|
|||
<a href="#resources" class="nav-link" data-action="sidebar-nav">Resources</a>
|
||||
<ul class="nav">
|
||||
<li class="nav-item">
|
||||
<a href="#books">Books</a>
|
||||
<a href="#books" class="nav-link" data-action="sidebar-nav">Books</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="#screencasts">Screencasts</a>
|
||||
<a href="#screencasts" class="nav-link" data-action="sidebar-nav">Screencasts</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="#examples">Examples</a>
|
||||
<a href="#examples" class="nav-link" data-action="sidebar-nav">Examples</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="#chat">Chat</a>
|
||||
<a href="#chat" class="nav-link" data-action="sidebar-nav">Chat</a>
|
||||
</li>
|
||||
<li class="nav-item">
|
||||
<a href="#annotated-source">Annotated Source</a>
|
||||
<a href="#annotated-source" class="nav-link" data-action="sidebar-nav">Annotated Source</a>
|
||||
</li>
|
||||
</ul>
|
||||
</li>
|
||||
|
|
@ -576,7 +589,7 @@ textarea {
|
|||
<pre><code>npm install -g coffee-script</code></pre></blockquote>
|
||||
|
||||
<h2>Overview</h2><p><em>CoffeeScript on the <span class="hidden-md-up">top</span><span class="hidden-sm-down">left</span>, compiled JavaScript output on the <span class="hidden-md-up">bottom</span><span class="hidden-sm-down">right</span>. The CoffeeScript is editable!</em></p>
|
||||
<aside class="code-example container-fluid" data-example="overview">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="overview">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="overview-coffee"># Assignment:
|
||||
|
|
@ -670,19 +683,13 @@ cubes = (function() {
|
|||
|
||||
</section>
|
||||
<section id="installation">
|
||||
<h2>Installation</h2><p>The CoffeeScript compiler is itself <a href="v2/annotated-source/grammar.html">written in CoffeeScript</a>, using the <a href="http://jison.org">Jison parser generator</a>. The command-line version of <code>coffee</code> is available as a <a href="http://nodejs.org/">Node.js</a> utility. The <a href="v2/browser-compiler/coffee-script.js">core compiler</a> however, does not depend on Node, and can be run in any JavaScript environment, or in the browser (see “Try CoffeeScript”, above).</p>
|
||||
<h2>Installation</h2><p>The command-line version of <code>coffee</code> is available as a <a href="http://nodejs.org/">Node.js</a> utility. The <a href="v2/browser-compiler/coffee-script.js">core compiler</a> however, does not depend on Node, and can be run in any JavaScript environment, or in the browser (see <a href="#try">Try CoffeeScript</a>).</p>
|
||||
<p>To install, first make sure you have a working copy of the latest stable version of <a href="http://nodejs.org/">Node.js</a>. You can then install CoffeeScript globally with <a href="http://npmjs.org">npm</a>:</p>
|
||||
<blockquote>
|
||||
<pre><code>npm install -g coffee-script</code></pre></blockquote>
|
||||
<p>When you need CoffeeScript as a dependency, install it locally:</p>
|
||||
<pre><code>npm install --global coffee-script</code></pre></blockquote>
|
||||
<p>When you need CoffeeScript as a dependency of a project, within that project’s folder you can install it locally:</p>
|
||||
<blockquote>
|
||||
<pre><code>npm install --save coffee-script</code></pre></blockquote>
|
||||
<p>If you’d prefer to install the latest <strong>master</strong> version of CoffeeScript, you can clone the CoffeeScript <a href="http://github.com/jashkenas/coffeescript">source repository</a> from GitHub, or download <a href="http://github.com/jashkenas/coffeescript/tarball/master">the source</a> directly. To install the latest master CoffeeScript compiler with npm:</p>
|
||||
<blockquote>
|
||||
<pre><code>npm install -g jashkenas/coffeescript</code></pre></blockquote>
|
||||
<p>Or, if you want to install to <code>/usr/local</code>, and don’t want to use npm to manage it, open the <code>coffee-script</code> directory and run:</p>
|
||||
<blockquote>
|
||||
<pre><code>sudo bin/cake install</code></pre></blockquote>
|
||||
|
||||
</section>
|
||||
<section id="usage">
|
||||
|
|
@ -733,14 +740,6 @@ cubes = (function() {
|
|||
|
||||
<tr>
|
||||
|
||||
<td><code>-j, --join [FILE]</code></td>
|
||||
|
||||
<td>Before compiling, concatenate all scripts together in the order they were passed, and write them into the specified file. (Deprecated.)</td>
|
||||
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
|
||||
<td><code>-w, --watch</code></td>
|
||||
|
||||
<td>Watch files for changes, rerunning the specified command when any file is updated.</td>
|
||||
|
|
@ -864,14 +863,14 @@ cubes = (function() {
|
|||
</section>
|
||||
<section id="language">
|
||||
<h2>Language Reference</h2><p><em>This reference is structured so that it can be read from top to bottom, if you like. Later sections use ideas and syntax previously introduced. Familiarity with JavaScript is assumed. In all of the following examples, the source CoffeeScript is provided on the left, and the direct compilation into JavaScript is on the right.</em></p>
|
||||
<p><em>Many of the examples can be run (where it makes sense) by pressing the <strong>run</strong> button on the right, and can be loaded into the “Try CoffeeScript” console by pressing the <strong>load</strong> button on the left.</em></p>
|
||||
<p><em>Many of the examples can be run (where it makes sense) by pressing the</em> <small>▶</small> <em>button on the right. The CoffeeScript on the left is editable, and the JavaScript will update as you edit.</em></p>
|
||||
<p>First, the basics: CoffeeScript uses significant whitespace to delimit blocks of code. You don’t need to use semicolons <code>;</code> to terminate expressions, ending the line will do just as well (although semicolons can still be used to fit multiple expressions onto a single line). Instead of using curly braces <code>{ }</code> to surround blocks of code in <a href="#literals">functions</a>, <a href="#conditionals">if-statements</a>, <a href="#switch">switch</a>, and <a href="#try">try/catch</a>, use indentation.</p>
|
||||
<p>You don’t need to use parentheses to invoke a function if you’re passing arguments. The implicit call wraps forward to the end of the line or block expression.<br>
|
||||
<code>console.log sys.inspect object</code> → <code>console.log(sys.inspect(object));</code></p>
|
||||
|
||||
<section id="functions">
|
||||
<h2>Functions</h2><p>Functions are defined by an optional list of parameters in parentheses, an arrow, and the function body. The empty function looks like this: <code>-></code></p>
|
||||
<aside class="code-example container-fluid" data-example="functions">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="functions">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="functions-coffee">square = (x) -> x * x
|
||||
|
|
@ -900,7 +899,7 @@ cube = function(x) {
|
|||
|
||||
</aside>
|
||||
<p>Functions may also have default values for arguments, which will be used if the incoming argument is missing (<code>undefined</code>).</p>
|
||||
<aside class="code-example container-fluid" data-example="default_args">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="default_args">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="default_args-coffee">fill = (container, liquid = "coffee") ->
|
||||
|
|
@ -928,7 +927,7 @@ fill = function(container, liquid = "coffee") {
|
|||
</section>
|
||||
<section id="strings">
|
||||
<h2>Strings</h2><p>Like JavaScript and many other languages, CoffeeScript supports strings as delimited by the <code>"</code> or <code>'</code> characters. CoffeeScript also supports string interpolation within <code>"</code>-quoted strings, using <code>#{ … }</code>. Single-quoted strings are literal. You may even use interpolation in object keys.</p>
|
||||
<aside class="code-example container-fluid" data-example="interpolation">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="interpolation">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="interpolation-coffee">author = "Wittgenstein"
|
||||
|
|
@ -957,7 +956,7 @@ sentence = `${22 / 7} is a decent approximation of π`;
|
|||
|
||||
</aside>
|
||||
<p>Multiline strings are allowed in CoffeeScript. Lines are joined by a single space unless they end with a backslash. Indentation is ignored.</p>
|
||||
<aside class="code-example container-fluid" data-example="strings">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="strings">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="strings-coffee">mobyDick = "Call me Ishmael. Some years ago --
|
||||
|
|
@ -984,7 +983,7 @@ mobyDick = "Call me Ishmael. Some years ago -- never mind how long precisely --
|
|||
|
||||
</aside>
|
||||
<p>Block strings, delimited by <code>"""</code> or <code>'''</code>, can be used to hold formatted or indentation-sensitive text (or, if you just don’t feel like escaping quotes and apostrophes). The indentation level that begins the block is maintained throughout, so you can keep it all aligned with the body of your code.</p>
|
||||
<aside class="code-example container-fluid" data-example="heredocs">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="heredocs">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="heredocs-coffee">html = """
|
||||
|
|
@ -1014,7 +1013,7 @@ html = "<strong>\n cup of coffeescript\n</strong>";
|
|||
</section>
|
||||
<section id="objects-and-arrays">
|
||||
<h2>Objects and Arrays</h2><p>The CoffeeScript literals for objects and arrays look very similar to their JavaScript cousins. When each property is listed on its own line, the commas are optional. Objects may be created using indentation instead of explicit braces, similar to <a href="http://yaml.org">YAML</a>.</p>
|
||||
<aside class="code-example container-fluid" data-example="objects_and_arrays">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="objects_and_arrays">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="objects_and_arrays-coffee">song = ["do", "re", "mi", "fa", "so"]
|
||||
|
|
@ -1070,16 +1069,16 @@ kids = {
|
|||
|
||||
</aside>
|
||||
<p>In JavaScript, you can’t use reserved words, like <code>class</code>, as properties of an object, without quoting them as strings. CoffeeScript notices reserved words used as keys in objects and quotes them for you, so you don’t have to worry about it (say, when using jQuery).</p>
|
||||
<aside class="code-example container-fluid" data-example="objects_reserved">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="objects_reserved">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="objects_reserved-coffee">$('.account').attr class: 'active'
|
||||
<textarea class="coffee-example" id="objects_reserved-coffee">$('.account').prop class: 'active'
|
||||
|
||||
log object.class
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="col-md-6 javascript-output-column">
|
||||
<textarea class="javascript-output" id="objects_reserved-js">$('.account').attr({
|
||||
<textarea class="javascript-output" id="objects_reserved-js">$('.account').prop({
|
||||
"class": 'active'
|
||||
});
|
||||
|
||||
|
|
@ -1090,7 +1089,7 @@ log(object["class"]);
|
|||
|
||||
</aside>
|
||||
<p>CoffeeScript has a shortcut for creating objects when you want the key to be set with a variable of the same name.</p>
|
||||
<aside class="code-example container-fluid" data-example="objects_shorthand">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="objects_shorthand">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="objects_shorthand-coffee">name = "Michelangelo"
|
||||
|
|
@ -1125,7 +1124,7 @@ output = `${turtle.name} wears an ${turtle.mask} mask. Watch out for his ${turtl
|
|||
</section>
|
||||
<section id="comments">
|
||||
<h2>Comments</h2><p>In CoffeeScript, comments are denoted by the <code>#</code> character. Everything from a <code>#</code> to the end of the line is ignored by the compiler, and will be excluded from the JavaScript output.</p>
|
||||
<aside class="code-example container-fluid" data-example="comment">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="comment">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="comment-coffee">code = 2 * 617 # The code is 1234
|
||||
|
|
@ -1141,7 +1140,7 @@ code = 2 * 617;
|
|||
|
||||
</aside>
|
||||
<p>Sometimes you’d like to pass a block comment through to the generated JavaScript. For example, when you need to embed a licensing header at the top of a file. Block comments, which mirror the syntax for block strings, are preserved in the generated output.</p>
|
||||
<aside class="code-example container-fluid" data-example="block_comment">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="block_comment">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="block_comment-coffee">###
|
||||
|
|
@ -1166,7 +1165,7 @@ Released under the MIT License
|
|||
</section>
|
||||
<section id="lexical-scope">
|
||||
<h2>Lexical Scoping and Variable Safety</h2><p>The CoffeeScript compiler takes care to make sure that all of your variables are properly declared within lexical scope — you never need to write <code>var</code> yourself.</p>
|
||||
<aside class="code-example container-fluid" data-example="scope">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="scope">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="scope-coffee">outer = 1
|
||||
|
|
@ -1208,7 +1207,7 @@ inner = changeNumbers();
|
|||
<section id="conditionals">
|
||||
<h2>If, Else, Unless, and Conditional Assignment</h2><p><strong>If/else</strong> statements can be written without the use of parentheses and curly brackets. As with functions and other block expressions, multi-line conditionals are delimited by indentation. There’s also a handy postfix form, with the <code>if</code> or <code>unless</code> at the end.</p>
|
||||
<p>CoffeeScript can compile <strong>if</strong> statements into JavaScript expressions, using the ternary operator when possible, and closure wrapping otherwise. There is no explicit ternary statement in CoffeeScript — you simply use a regular <strong>if</strong> statement on a single line.</p>
|
||||
<aside class="code-example container-fluid" data-example="conditionals">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="conditionals">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="conditionals-coffee">mood = greatlyImproved if singing
|
||||
|
|
@ -1246,7 +1245,7 @@ date = friday ? sue : jill;
|
|||
</section>
|
||||
<section id="splats">
|
||||
<h2>Splats…</h2><p>The JavaScript <strong>arguments object</strong> is a useful way to work with functions that accept variable numbers of arguments. CoffeeScript provides splats <code>...</code>, both for function definition as well as invocation, making variable numbers of arguments a little bit more palatable.</p>
|
||||
<aside class="code-example container-fluid" data-example="splats">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="splats">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="splats-coffee">gold = silver = rest = "unknown"
|
||||
|
|
@ -1311,7 +1310,7 @@ alert("The Field: " + rest);
|
|||
</section>
|
||||
<section id="loops">
|
||||
<h2>Loops and Comprehensions</h2><p>Most of the loops you’ll write in CoffeeScript will be <strong>comprehensions</strong> over arrays, objects, and ranges. Comprehensions replace (and compile into) <strong>for</strong> loops, with optional guard clauses and the value of the current array index. Unlike for loops, array comprehensions are expressions, and can be returned and assigned.</p>
|
||||
<aside class="code-example container-fluid" data-example="array_comprehensions">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="array_comprehensions">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="array_comprehensions-coffee"># Eat lunch.
|
||||
|
|
@ -1358,7 +1357,7 @@ for (l = 0, len2 = foods.length; l < len2; l++) {
|
|||
<p>Comprehensions should be able to handle most places where you otherwise would use a loop, <strong>each</strong>/<strong>forEach</strong>, <strong>map</strong>, or <strong>select</strong>/<strong>filter</strong>, for example:<br>
|
||||
<code>shortNames = (name for name in list when name.length < 5)</code><br>
|
||||
If you know the start and end of your loop, or would like to step through in fixed-size increments, you can use a range to specify the start and end of your comprehension.</p>
|
||||
<aside class="code-example container-fluid" data-example="range_comprehensions">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="range_comprehensions">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="range_comprehensions-coffee">countdown = (num for num in [10..1])
|
||||
|
|
@ -1392,7 +1391,7 @@ countdown = (function() {
|
|||
<p>If you don’t need the current iteration value you may omit it:
|
||||
<code>browser.closeCurrentTab() for [0...count]</code></p>
|
||||
<p>Comprehensions can also be used to iterate over the keys and values in an object. Use <code>of</code> to signal comprehension over the properties of an object instead of the values in an array.</p>
|
||||
<aside class="code-example container-fluid" data-example="object_comprehensions">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="object_comprehensions">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="object_comprehensions-coffee">yearsOld = max: 10, ida: 9, tim: 11
|
||||
|
|
@ -1433,7 +1432,7 @@ ages = (function() {
|
|||
<p>If you would like to iterate over just the keys that are defined on the object itself, by adding a <code>hasOwnProperty</code> check to avoid properties that may be inherited from the prototype, use <code>for own key, value of object</code>.</p>
|
||||
<p>To iterate a generator function, use <code>from</code>. See <a href="#generator-iteration">Generator Functions</a>.</p>
|
||||
<p>The only low-level loop that CoffeeScript provides is the <strong>while</strong> loop. The main difference from JavaScript is that the <strong>while</strong> loop can be used as an expression, returning an array containing the result of each iteration through the loop.</p>
|
||||
<aside class="code-example container-fluid" data-example="while">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="while">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="while-coffee"># Econ 101
|
||||
|
|
@ -1483,7 +1482,7 @@ lyrics = (function() {
|
|||
</aside>
|
||||
<p>For readability, the <strong>until</strong> keyword is equivalent to <code>while not</code>, and the <strong>loop</strong> keyword is equivalent to <code>while true</code>.</p>
|
||||
<p>When using a JavaScript loop to generate functions, it’s common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don’t just share the final values. CoffeeScript provides the <code>do</code> keyword, which immediately invokes a passed function, forwarding any arguments.</p>
|
||||
<aside class="code-example container-fluid" data-example="do">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="do">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="do-coffee">for filename in list
|
||||
|
|
@ -1513,7 +1512,7 @@ for (i = 0, len = list.length; i < len; i++) {
|
|||
</section>
|
||||
<section id="slices">
|
||||
<h2>Array Slicing and Splicing with Ranges</h2><p>Ranges can also be used to extract slices of arrays. With two dots (<code>3..6</code>), the range is inclusive (<code>3, 4, 5, 6</code>); with three dots (<code>3...6</code>), the range excludes the end (<code>3, 4, 5</code>). Slices indices have useful defaults. An omitted first index defaults to zero and an omitted second index defaults to the size of the array.</p>
|
||||
<aside class="code-example container-fluid" data-example="slices">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="slices">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="slices-coffee">numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
|
|
@ -1551,7 +1550,7 @@ copy = numbers.slice(0);
|
|||
|
||||
</aside>
|
||||
<p>The same syntax can be used with assignment to replace a segment of an array with new values, splicing it.</p>
|
||||
<aside class="code-example container-fluid" data-example="splices">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="splices">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="splices-coffee">numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||
|
|
@ -1581,7 +1580,7 @@ numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
|
|||
</section>
|
||||
<section id="expressions">
|
||||
<h2>Everything is an Expression (at least, as much as possible)</h2><p>You might have noticed how even though we don’t add return statements to CoffeeScript functions, they nonetheless return their final value. The CoffeeScript compiler tries to make sure that all statements in the language can be used as expressions. Watch how the <code>return</code> gets pushed down into each possible branch of execution in the function below.</p>
|
||||
<aside class="code-example container-fluid" data-example="expressions">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="expressions">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="expressions-coffee">grade = (student) ->
|
||||
|
|
@ -1626,7 +1625,7 @@ eldest = 24 > 21 ? "Liz" : "Ike";
|
|||
</aside>
|
||||
<p>Even though functions will always return their final value, it’s both possible and encouraged to return early from a function body writing out the explicit return (<code>return value</code>), when you know that you’re done.</p>
|
||||
<p>Because variable declarations occur at the top of scope, assignment can be used within expressions, even for variables that haven’t been seen before:</p>
|
||||
<aside class="code-example container-fluid" data-example="expressions_assignment">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="expressions_assignment">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="expressions_assignment-coffee">six = (one = 1) + (two = 2) + (three = 3)
|
||||
|
|
@ -1648,7 +1647,7 @@ six = (one = 1) + (two = 2) + (three = 3);
|
|||
|
||||
</aside>
|
||||
<p>Things that would otherwise be statements in JavaScript, when used as part of an expression in CoffeeScript, are converted into expressions by wrapping them in a closure. This lets you do useful things, like assign the result of a comprehension to a variable:</p>
|
||||
<aside class="code-example container-fluid" data-example="expressions_comprehension">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="expressions_comprehension">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="expressions_comprehension-coffee"># The first ten global properties.
|
||||
|
|
@ -1679,7 +1678,7 @@ globals = ((function() {
|
|||
|
||||
</aside>
|
||||
<p>As well as silly things, like passing a <strong>try/catch</strong> statement directly into a function call:</p>
|
||||
<aside class="code-example container-fluid" data-example="expressions_try">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="expressions_try">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="expressions_try-coffee">alert(
|
||||
|
|
@ -1725,7 +1724,7 @@ alert((function() {
|
|||
<p>As a shortcut for <code>this.property</code>, you can use <code>@property</code>.</p>
|
||||
<p>You can use <code>in</code> to test for array presence, and <code>of</code> to test for JavaScript object-key presence.</p>
|
||||
<p>To simplify math expressions, <code>**</code> can be used for exponentiation and <code>//</code> performs integer division. <code>%</code> works just like in JavaScript, while <code>%%</code> provides <a href="http://en.wikipedia.org/wiki/Modulo_operation">“dividend dependent modulo”</a>:</p>
|
||||
<aside class="code-example container-fluid" data-example="modulo">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="modulo">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="modulo-coffee">-7 % 5 == -2 # The remainder of 7 / 5
|
||||
|
|
@ -1810,7 +1809,7 @@ tabs.selectTabAtIndex(modulo(tabs.currentIndex - count, tabs.length));
|
|||
|
||||
<tr>
|
||||
|
||||
<td><code>false</code>, <code>no</code>, <code>off</code></td>
|
||||
<td><code>false</code>, <code>no</code>, <code>off</code> </td>
|
||||
|
||||
<td><code>false</code></td>
|
||||
|
||||
|
|
@ -1868,7 +1867,7 @@ tabs.selectTabAtIndex(modulo(tabs.currentIndex - count, tabs.length));
|
|||
|
||||
</table>
|
||||
|
||||
<aside class="code-example container-fluid" data-example="aliases">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="aliases">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="aliases-coffee">launch() if ignition is on
|
||||
|
|
@ -1918,7 +1917,7 @@ print(inspect(`My name is ${this.name}`));
|
|||
<section id="existential-operator">
|
||||
<h2>The Existential Operator</h2><p>It’s a little difficult to check for the existence of a variable in JavaScript. <code>if (variable) …</code> comes close, but fails for zero, the empty string, and false. CoffeeScript’s existential operator <code>?</code> returns true unless a variable is <strong>null</strong> or <strong>undefined</strong>, which makes it analogous to Ruby’s <code>nil?</code></p>
|
||||
<p>It can also be used for safer conditional assignment than <code>||=</code> provides, for cases where you may be handling numbers or strings.</p>
|
||||
<aside class="code-example container-fluid" data-example="existence">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="existence">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="existence-coffee">solipsism = true if mind? and not world?
|
||||
|
|
@ -1955,7 +1954,7 @@ footprints = typeof yeti !== "undefined" && yeti !== null ? yeti : "bear";
|
|||
|
||||
</aside>
|
||||
<p>The accessor variant of the existential operator <code>?.</code> can be used to soak up null references in a chain of properties. Use it instead of the dot accessor <code>.</code> in cases where the base value may be <strong>null</strong> or <strong>undefined</strong>. If all of the properties exist then you’ll get the expected result, if the chain is broken, <strong>undefined</strong> is returned instead of the <strong>TypeError</strong> that would be raised otherwise.</p>
|
||||
<aside class="code-example container-fluid" data-example="soaks">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="soaks">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="soaks-coffee">zip = lottery.drawWinner?().address?.zipcode
|
||||
|
|
@ -1977,7 +1976,7 @@ zip = typeof lottery.drawWinner === "function" ? (ref = lottery.drawWinner().add
|
|||
<h2>Classes, Inheritance, and Super</h2><p>JavaScript’s prototypal inheritance has always been a bit of a brain-bender, with a whole family tree of libraries that provide a cleaner syntax for classical inheritance on top of JavaScript’s prototypes: <a href="http://code.google.com/p/base2/">Base2</a>, <a href="http://prototypejs.org/">Prototype.js</a>, <a href="http://jsclass.jcoglan.com/">JS.Class</a>, etc. The libraries provide syntactic sugar, but the built-in inheritance would be completely usable if it weren’t for a couple of small exceptions: it’s awkward to call <strong>super</strong> (the prototype object’s implementation of the current function), and it’s awkward to correctly set the prototype chain.</p>
|
||||
<p>Instead of repetitively attaching functions to a prototype, CoffeeScript provides a basic <code>class</code> structure that allows you to name your class, set the superclass, assign prototypal properties, and define the constructor, in a single assignable expression.</p>
|
||||
<p>Constructor functions are named, to better support helpful stack traces. In the first class in the example below, <code>this.constructor.name is "Animal"</code>.</p>
|
||||
<aside class="code-example container-fluid" data-example="classes">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="classes">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="classes-coffee">class Animal
|
||||
|
|
@ -2072,7 +2071,7 @@ tom.move();
|
|||
|
||||
</aside>
|
||||
<p>If structuring your prototypes classically isn’t your cup of tea, CoffeeScript provides a couple of lower-level conveniences. The <code>extends</code> operator helps with proper prototype setup, and can be used to create an inheritance chain between any pair of constructor functions; <code>::</code> gives you quick access to an object’s prototype; and <code>super()</code> is converted into a call against the immediate ancestor’s method of the same name.</p>
|
||||
<aside class="code-example container-fluid" data-example="prototypes">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="prototypes">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="prototypes-coffee">String::dasherize = ->
|
||||
|
|
@ -2100,7 +2099,7 @@ tom.move();
|
|||
</section>
|
||||
<section id="destructuring">
|
||||
<h2>Destructuring Assignment</h2><p>Just like JavaScript (since ES2015), CoffeeScript has destructuring assignment syntax. When you assign an array or object literal to a value, CoffeeScript breaks up and matches both sides against each other, assigning the values on the right to the variables on the left. In the simplest case, it can be used for parallel assignment:</p>
|
||||
<aside class="code-example container-fluid" data-example="parallel_assignment">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="parallel_assignment">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="parallel_assignment-coffee">theBait = 1000
|
||||
|
|
@ -2129,7 +2128,7 @@ ref = [theSwitch, theBait], theBait = ref[0], theSwitch = ref[1];
|
|||
|
||||
</aside>
|
||||
<p>But it’s also helpful for dealing with functions that return multiple values.</p>
|
||||
<aside class="code-example container-fluid" data-example="multiple_return_values">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="multiple_return_values">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="multiple_return_values-coffee">weatherReport = (location) ->
|
||||
|
|
@ -2159,7 +2158,7 @@ ref = weatherReport("Berkeley, CA"), city = ref[0], temp = ref[1], forecast = re
|
|||
|
||||
</aside>
|
||||
<p>Destructuring assignment can be used with any depth of array and object nesting, to help pull out deeply nested properties.</p>
|
||||
<aside class="code-example container-fluid" data-example="object_extraction">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="object_extraction">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="object_extraction-coffee">futurists =
|
||||
|
|
@ -2200,7 +2199,7 @@ ref = futurists.poet, name = ref.name, (ref1 = ref.address, street = ref1[0], ci
|
|||
|
||||
</aside>
|
||||
<p>Destructuring assignment can even be combined with splats.</p>
|
||||
<aside class="code-example container-fluid" data-example="patterns_and_splats">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="patterns_and_splats">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="patterns_and_splats-coffee">tag = "<impossible>"
|
||||
|
|
@ -2227,7 +2226,7 @@ ref = tag.split(""), open = ref[0], contents = 3 <= ref.length ? slice.call(ref,
|
|||
|
||||
</aside>
|
||||
<p>Expansion can be used to retrieve elements from the end of an array without having to assign the rest of its values. It works in function parameter lists as well.</p>
|
||||
<aside class="code-example container-fluid" data-example="expansion">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="expansion">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="expansion-coffee">text = "Every literary critic believes he will
|
||||
|
|
@ -2254,7 +2253,7 @@ ref = text.split(" "), first = ref[0], last = ref[ref.length - 1];
|
|||
|
||||
</aside>
|
||||
<p>Destructuring assignment is also useful when combined with class constructors to assign properties to your instance from an options object passed to the constructor.</p>
|
||||
<aside class="code-example container-fluid" data-example="constructor_destructuring">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="constructor_destructuring">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="constructor_destructuring-coffee">class Person
|
||||
|
|
@ -2296,9 +2295,9 @@ tim = new Person({
|
|||
|
||||
</section>
|
||||
<section id="fat-arrow">
|
||||
<h2>Bound Functions, Generator Functions</h2><p>In JavaScript, the <code>this</code> keyword is dynamically scoped to mean the object that the current function is attached to. If you pass a function as a callback or attach it to a different object, the original value of <code>this</code> will be lost. If you’re not familiar with this behavior, <a href="http://64.13.255.16/articles/scope_in_javascript/">this Digital Web article</a> gives a good overview of the quirks.</p>
|
||||
<h2>Function Modifiers</h2><p>In JavaScript, the <code>this</code> keyword is dynamically scoped to mean the object that the current function is attached to. If you pass a function as a callback or attach it to a different object, the original value of <code>this</code> will be lost. If you’re not familiar with this behavior, <a href="http://64.13.255.16/articles/scope_in_javascript/">this Digital Web article</a> gives a good overview of the quirks.</p>
|
||||
<p>The fat arrow <code>=></code> can be used to both define a function, and to bind it to the current value of <code>this</code>, right on the spot. This is helpful when using callback-based libraries like Prototype or jQuery, for creating iterator functions to pass to <code>each</code>, or event-handler functions to use with <code>on</code>. Functions created with the fat arrow are able to access properties of the <code>this</code> where they’re defined.</p>
|
||||
<aside class="code-example container-fluid" data-example="fat_arrow">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="fat_arrow">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="fat_arrow-coffee">Account = (customer, cart) ->
|
||||
|
|
@ -2326,8 +2325,8 @@ Account = function(customer, cart) {
|
|||
</aside>
|
||||
<p>If we had used <code>-></code> in the callback above, <code>@customer</code> would have referred to the undefined “customer” property of the DOM element, and trying to call <code>purchase()</code> on it would have raised an exception.</p>
|
||||
<p>When used in a class definition, methods declared with the fat arrow will be automatically bound to each instance of the class when the instance is constructed.</p>
|
||||
<p>CoffeeScript functions also support <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">ES2015 generator functions</a> through the <code>yield</code> keyword. There’s no <code>function*(){}</code> nonsense — a generator in CoffeeScript is simply a function that yields.</p>
|
||||
<aside class="code-example container-fluid" data-example="generators">
|
||||
<p>CoffeeScript also supports <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">generator functions</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">async functions</a> through the <code>yield</code> and <code>await</code> keywords respectively. There's no <code>function*(){}</code> or <code>async function(){}</code> nonsense — a generator in CoffeeScript is simply a function that yields, and an async function in CoffeeScript is simply a function that awaits.</p>
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="generators">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="generators-coffee">perfectSquares = ->
|
||||
|
|
@ -2366,7 +2365,7 @@ window.ps || (window.ps = perfectSquares());
|
|||
</aside>
|
||||
<p><code>yield*</code> is called <code>yield from</code>, and <code>yield return</code> may be used if you need to force a generator that doesn’t yield.</p>
|
||||
<p>You can iterate over a generator function using <code>for…from</code>.</p>
|
||||
<aside class="code-example container-fluid" data-example="generator_iteration">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="generator_iteration">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="generator_iteration-coffee">fibonacci = ->
|
||||
|
|
@ -2419,87 +2418,61 @@ getFibonacciNumbers = function(length) {
|
|||
</div>
|
||||
|
||||
</aside>
|
||||
|
||||
</section>
|
||||
<section id="embedded">
|
||||
<h2>Embedded JavaScript</h2><p>Hopefully, you’ll never need to use it, but if you ever need to intersperse snippets of JavaScript within your CoffeeScript, you can use backticks to pass it straight through.</p>
|
||||
<aside class="code-example container-fluid" data-example="embedded">
|
||||
<p>Similar to how <code>yield return</code> forces a generator, <code>await return</code> may be used to force a function to be async.</p>
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="async">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="embedded-coffee">hi = `function() {
|
||||
return [document.title, "Hello JavaScript"].join(": ");
|
||||
}`
|
||||
<textarea class="coffee-example" id="async-coffee"># Your browser must support async/await and speech synthesis
|
||||
# to run this example.
|
||||
|
||||
sleep = (ms) ->
|
||||
new Promise (resolve) ->
|
||||
window.setTimeout resolve, ms
|
||||
|
||||
say = (text) ->
|
||||
window.speechSynthesis.cancel()
|
||||
window.speechSynthesis.speak new SpeechSynthesisUtterance text
|
||||
|
||||
countdown = (seconds) ->
|
||||
for i in [seconds..1]
|
||||
say i
|
||||
await sleep 1000 # wait one second
|
||||
say "Blastoff!"
|
||||
|
||||
countdown 3
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="col-md-6 javascript-output-column">
|
||||
<textarea class="javascript-output" id="embedded-js">var hi;
|
||||
<textarea class="javascript-output" id="async-js">var countdown, say, sleep;
|
||||
|
||||
hi = function() {
|
||||
return [document.title, "Hello JavaScript"].join(": ");
|
||||
sleep = function(ms) {
|
||||
return new Promise(function(resolve) {
|
||||
return window.setTimeout(resolve, ms);
|
||||
});
|
||||
};
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-xs-12 text-xs-right">
|
||||
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="embedded" data-run="hi%28%29"><small>▶</small> hi()</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</aside>
|
||||
<p>Escape backticks with backslashes: <code>\`</code> becomes <code>`</code>.</p>
|
||||
<p>Escape backslashes before backticks with more backslashes: <code>\\\`</code> becomes <code>\`</code>.</p>
|
||||
<aside class="code-example container-fluid" data-example="embedded_escaped">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="embedded_escaped-coffee">markdown = `function () {
|
||||
return \`In Markdown, write code like \\\`this\\\`\`;
|
||||
}`
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="col-md-6 javascript-output-column">
|
||||
<textarea class="javascript-output" id="embedded_escaped-js">var markdown;
|
||||
|
||||
markdown = function () {
|
||||
return `In Markdown, write code like \`this\``;
|
||||
say = function(text) {
|
||||
window.speechSynthesis.cancel();
|
||||
return window.speechSynthesis.speak(new SpeechSynthesisUtterance(text));
|
||||
};
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-xs-12 text-xs-right">
|
||||
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="embedded_escaped" data-run="markdown%28%29"><small>▶</small> markdown()</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</aside>
|
||||
<p>You can also embed blocks of JavaScript using triple backticks. That’s easier than escaping backticks, if you need them inside your JavaScript block.</p>
|
||||
<aside class="code-example container-fluid" data-example="embedded_block">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="embedded_block-coffee">```
|
||||
function time() {
|
||||
return `The time is ${new Date().toLocaleTimeString()}`;
|
||||
}
|
||||
```
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="col-md-6 javascript-output-column">
|
||||
<textarea class="javascript-output" id="embedded_block-js">
|
||||
function time() {
|
||||
return `The time is ${new Date().toLocaleTimeString()}`;
|
||||
}
|
||||
;
|
||||
|
||||
countdown = async function(seconds) {
|
||||
var i, j, ref;
|
||||
for (i = j = ref = seconds; ref <= 1 ? j <= 1 : j >= 1; i = ref <= 1 ? ++j : --j) {
|
||||
say(i);
|
||||
await sleep(1000);
|
||||
}
|
||||
return say("Blastoff!");
|
||||
};
|
||||
|
||||
countdown(3);
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-xs-12 text-xs-right">
|
||||
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="embedded_block" data-run="time%28%29"><small>▶</small> time()</button>
|
||||
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="async" data-run="true">▶</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
@ -2509,7 +2482,7 @@ function time() {
|
|||
<section id="switch">
|
||||
<h2>Switch/When/Else</h2><p><strong>Switch</strong> statements in JavaScript are a bit awkward. You need to remember to <strong>break</strong> at the end of every <strong>case</strong> statement to avoid accidentally falling through to the default case. CoffeeScript prevents accidental fall-through, and can convert the <code>switch</code> into a returnable, assignable expression. The format is: <code>switch</code> condition, <code>when</code> clauses, <code>else</code> the default case.</p>
|
||||
<p>As in Ruby, <strong>switch</strong> statements in CoffeeScript can take multiple values for each <strong>when</strong> clause. If any of the values match, the clause runs.</p>
|
||||
<aside class="code-example container-fluid" data-example="switch">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="switch">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="switch-coffee">switch day
|
||||
|
|
@ -2554,7 +2527,7 @@ function time() {
|
|||
|
||||
</aside>
|
||||
<p>Switch statements can also be used without a control expression, turning them in to a cleaner alternative to if/else chains.</p>
|
||||
<aside class="code-example container-fluid" data-example="switch_with_no_expression">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="switch_with_no_expression">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="switch_with_no_expression-coffee">score = 76
|
||||
|
|
@ -2595,7 +2568,7 @@ grade = (function() {
|
|||
</section>
|
||||
<section id="try">
|
||||
<h2>Try/Catch/Finally</h2><p>Try-expressions have the same semantics as try-statements in JavaScript, though in CoffeeScript, you may omit <em>both</em> the catch and finally parts. The catch part may also omit the error parameter if it is not needed.</p>
|
||||
<aside class="code-example container-fluid" data-example="try">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="try">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="try-coffee">try
|
||||
|
|
@ -2628,7 +2601,7 @@ try {
|
|||
</section>
|
||||
<section id="comparisons">
|
||||
<h2>Chained Comparisons</h2><p>CoffeeScript borrows <a href="http://docs.python.org/reference/expressions.html#notin">chained comparisons</a> from Python — making it easy to test if a value falls within a certain range.</p>
|
||||
<aside class="code-example container-fluid" data-example="comparisons">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="comparisons">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="comparisons-coffee">cholesterol = 127
|
||||
|
|
@ -2657,7 +2630,7 @@ healthy = (200 > cholesterol && cholesterol > 60);
|
|||
</section>
|
||||
<section id="regexes">
|
||||
<h2>Block Regular Expressions</h2><p>Similar to block strings and comments, CoffeeScript supports block regexes — extended regular expressions that ignore internal whitespace and can contain comments and interpolation. Modeled after Perl’s <code>/x</code> modifier, CoffeeScript’s block regexes are delimited by <code>///</code> and go a long way towards making complex regular expressions readable. To quote from the CoffeeScript source:</p>
|
||||
<aside class="code-example container-fluid" data-example="heregexes">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="heregexes">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="heregexes-coffee">OPERATOR = /// ^ (
|
||||
|
|
@ -2684,8 +2657,7 @@ OPERATOR = /^(?:[-=]>|[-+*\/%<>&|^!?=]=|>>>=?|([-+:])\1|([&|<>])\2=?|\?\.|\.{2,3
|
|||
</section>
|
||||
<section id="tagged-template-literals">
|
||||
<h2>Tagged Template Literals</h2><p>CoffeeScript supports <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals">ES2015 tagged template literals</a>, which enable customized string interpolation. If you immediately prefix a string with a function name (no space between the two), CoffeeScript will output this “function plus string” combination as an ES2015 tagged template literal, which will <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals#Tagged_template_literals">behave accordingly</a>: the function is called, with the parameters being the input text and expression parts that make up the interpolated string. The function can then assemble these parts into an output string, providing custom string interpolation.</p>
|
||||
<p>Be aware that the CoffeeScript compiler is outputting ES2015 syntax for this feature, so your target JavaScript runtime(s) must support this syntax for your code to work; or you could use tools like <a href="http://babeljs.io/">Babel</a> or <a href="https://github.com/google/traceur-compiler">Traceur Compiler</a> to convert this ES2015 syntax into compatible JavaScript.</p>
|
||||
<aside class="code-example container-fluid" data-example="tagged_template_literals">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="tagged_template_literals">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="tagged_template_literals-coffee">upperCaseExpr = (textParts, expressions...) ->
|
||||
|
|
@ -2725,7 +2697,7 @@ greet = function(name, adjective) {
|
|||
</section>
|
||||
<section id="modules">
|
||||
<h2>Modules</h2><p>ES2015 modules are supported in CoffeeScript, with very similar <code>import</code> and <code>export</code> syntax:</p>
|
||||
<aside class="code-example container-fluid" data-example="modules">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="modules">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="modules-coffee">import 'local-file.coffee'
|
||||
|
|
@ -2826,6 +2798,91 @@ export {
|
|||
<p>Note that the CoffeeScript compiler <strong>does not resolve modules</strong>; writing an <code>import</code> or <code>export</code> statement in CoffeeScript will produce an <code>import</code> or <code>export</code> statement in the resulting output. It is your responsibility attach another transpiler, such as <a href="https://github.com/google/traceur-compiler">Traceur Compiler</a>, <a href="http://babeljs.io/">Babel</a> or <a href="https://github.com/rollup/rollup">Rollup</a>, to convert this ES2015 syntax into code that will work in your target runtimes.</p>
|
||||
<p>Also note that any file with an <code>import</code> or <code>export</code> statement will be output without a <a href="#lexical-scope">top-level function safety wrapper</a>; in other words, importing or exporting modules will automatically trigger <a href="#usage">bare</a> mode for that file. This is because per the ES2015 spec, <code>import</code> or <code>export</code> statements must occur at the topmost scope.</p>
|
||||
|
||||
</section>
|
||||
<section id="embedded">
|
||||
<h2>Embedded JavaScript</h2><p>Hopefully, you’ll never need to use it, but if you ever need to intersperse snippets of JavaScript within your CoffeeScript, you can use backticks to pass it straight through.</p>
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="embedded">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="embedded-coffee">hi = `function() {
|
||||
return [document.title, "Hello JavaScript"].join(": ");
|
||||
}`
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="col-md-6 javascript-output-column">
|
||||
<textarea class="javascript-output" id="embedded-js">var hi;
|
||||
|
||||
hi = function() {
|
||||
return [document.title, "Hello JavaScript"].join(": ");
|
||||
};
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-xs-12 text-xs-right">
|
||||
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="embedded" data-run="hi%28%29"><small>▶</small> hi()</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</aside>
|
||||
<p>Escape backticks with backslashes: <code>\`</code> becomes <code>`</code>.</p>
|
||||
<p>Escape backslashes before backticks with more backslashes: <code>\\\`</code> becomes <code>\`</code>.</p>
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="embedded_escaped">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="embedded_escaped-coffee">markdown = `function () {
|
||||
return \`In Markdown, write code like \\\`this\\\`\`;
|
||||
}`
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="col-md-6 javascript-output-column">
|
||||
<textarea class="javascript-output" id="embedded_escaped-js">var markdown;
|
||||
|
||||
markdown = function () {
|
||||
return `In Markdown, write code like \`this\``;
|
||||
};
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-xs-12 text-xs-right">
|
||||
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="embedded_escaped" data-run="markdown%28%29"><small>▶</small> markdown()</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</aside>
|
||||
<p>You can also embed blocks of JavaScript using triple backticks. That’s easier than escaping backticks, if you need them inside your JavaScript block.</p>
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="embedded_block">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="embedded_block-coffee">```
|
||||
function time() {
|
||||
return `The time is ${new Date().toLocaleTimeString()}`;
|
||||
}
|
||||
```
|
||||
</textarea>
|
||||
</div>
|
||||
<div class="col-md-6 javascript-output-column">
|
||||
<textarea class="javascript-output" id="embedded_block-js">
|
||||
function time() {
|
||||
return `The time is ${new Date().toLocaleTimeString()}`;
|
||||
}
|
||||
;
|
||||
|
||||
</textarea>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="row">
|
||||
<div class="col-xs-12 text-xs-right">
|
||||
<button type="button" class="btn btn-primary" data-action="run-code-example" data-example="embedded_block" data-run="time%28%29"><small>▶</small> time()</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</aside>
|
||||
|
||||
</section>
|
||||
</section>
|
||||
<section id="literate">
|
||||
|
|
@ -2834,14 +2891,14 @@ export {
|
|||
|
||||
</section>
|
||||
<section id="source-maps">
|
||||
<h2>Source Maps</h2><p>CoffeeScript 1.6.1 and above include support for generating source maps, a way to tell your JavaScript engine what part of your CoffeeScript program matches up with the code being evaluated. Browsers that support it can automatically use source maps to show your original source code in the debugger. To generate source maps alongside your JavaScript files, pass the <code>--map</code> or <code>-m</code> flag to the compiler.</p>
|
||||
<h2>Source Maps</h2><p>CoffeeScript includes support for generating source maps, a way to tell your JavaScript engine what part of your CoffeeScript program matches up with the code being evaluated. Browsers that support it can automatically use source maps to show your original source code in the debugger. To generate source maps alongside your JavaScript files, pass the <code>--map</code> or <code>-m</code> flag to the compiler.</p>
|
||||
<p>For a full introduction to source maps, how they work, and how to hook them up in your browser, read the <a href="http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/">HTML5 Tutorial</a>.</p>
|
||||
|
||||
</section>
|
||||
<section id="cake">
|
||||
<h2>Cake, and Cakefiles</h2><p>CoffeeScript includes a (very) simple build system similar to <a href="http://www.gnu.org/software/make/">Make</a> and <a href="http://rake.rubyforge.org/">Rake</a>. Naturally, it’s called Cake, and is used for the tasks that build and test the CoffeeScript language itself. Tasks are defined in a file named <code>Cakefile</code>, and can be invoked by running <code>cake [task]</code> from within the directory. To print a list of all the tasks and options, just type <code>cake</code>.</p>
|
||||
<p>Task definitions are written in CoffeeScript, so you can put arbitrary code in your Cakefile. Define a task with a name, a long description, and the function to invoke when the task is run. If your task takes a command-line option, you can define the option with short and long flags, and it will be made available in the <code>options</code> object. Here’s a task that uses the Node.js API to rebuild CoffeeScript’s parser:</p>
|
||||
<aside class="code-example container-fluid" data-example="cake_tasks">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="cake_tasks">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="cake_tasks-coffee">fs = require 'fs'
|
||||
|
|
@ -2879,7 +2936,7 @@ task('build:parser', 'rebuild the Jison parser', function(options) {
|
|||
</section>
|
||||
<section id="scripts">
|
||||
<h2><code>"text/coffeescript"</code> Script Tags</h2><p>While it’s not recommended for serious use, CoffeeScripts may be included directly within the browser using <code><script type="text/coffeescript"></code> tags. The source includes a compressed and minified version of the compiler (<a href="v2/browser-compiler/coffee-script.js">Download current version here, 51k when gzipped</a>) as <code>v2/browser-compiler/coffee-script.js</code>. Include this file on a page with inline CoffeeScript tags, and it will compile and evaluate them in order.</p>
|
||||
<p>In fact, the little bit of glue script that runs “Try CoffeeScript” above, as well as the jQuery for the menu, is implemented in just this way. View source and look at the bottom of the page to see the example. Including the script also gives you access to <code>CoffeeScript.compile()</code> so you can pop open Firebug and try compiling some strings.</p>
|
||||
<p>In fact, the little bit of glue script that runs <a href="#try">Try CoffeeScript</a>, as well as the code examples and other interactive parts of this site, is implemented in just this way. View source and look at the bottom of the page to see the example. Including the script also gives you access to <code>CoffeeScript.compile()</code> so you can pop open your JavaScript console and try compiling some strings.</p>
|
||||
<p>The usual caveats about CoffeeScript apply — your inline scripts will run within a closure wrapper, so if you want to expose global variables or functions, attach them to the <code>window</code> object.</p>
|
||||
|
||||
</section>
|
||||
|
|
@ -3122,7 +3179,7 @@ six = ->
|
|||
<li>Improved error messages, source maps and stack traces. Source maps now use the updated <code>//#</code> syntax.</li>
|
||||
<li>Leading <code>.</code> now closes all open calls, allowing for simpler chaining syntax.</li>
|
||||
</ul>
|
||||
<aside class="code-example container-fluid" data-example="chaining">
|
||||
<aside class="code-example container-fluid bg-ribbed-dark" data-example="chaining">
|
||||
<div class="row">
|
||||
<div class="col-md-6 coffee-example-column">
|
||||
<textarea class="coffee-example" id="chaining-coffee">$ 'body'
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue