1. Trang chủ
  2. » Công Nghệ Thông Tin

The little book on coffeescript the javascript developers guide to building better web apps

60 73 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 60
Dung lượng 5,64 MB

Nội dung

The Little Book on CoffeeScript Alex MacCaw Beijing • Cambridge • Farnham • Kưln • Sebastopol • Tokyo The Little Book on CoffeeScript by Alex MacCaw Copyright © 2012 Alex MacCaw All rights reserved Printed in the United States of America Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472 O’Reilly books may be purchased for educational, business, or sales promotional use Online editions are also available for most titles (http://my.safaribooksonline.com) For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com Editor: Mary Treseler Production Editor: Jasmine Perez Proofreader: O’Reilly Production Services Cover Designer: Karen Montgomery Interior Designer: David Futato Illustrator: Robert Romano Revision History for the First Edition: 2012-01-17 First release See http://oreilly.com/catalog/errata.csp?isbn=9781449321055 for release details Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc The Little Book on CoffeeScript and related trade dress are trademarks of O’Reilly Media, Inc Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks Where those designations appear in this book, and O’Reilly Media, Inc was aware of a trademark claim, the designations have been printed in caps or initial caps While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein ISBN: 978-1-449-32105-5 [LSI] 1326293686 Table of Contents Preface v CoffeeScript Syntax Variables and Scope Functions Function Arguments Function Invocation Function Context Object Literals and Array Definition Flow Control String Interpolation Loops and Comprehensions Arrays Aliases and the Existential Operator 2 3 4 6 7 CoffeeScript Classes Instance Properties Static Properties Inheritance and Super Mixins Extending Classes 10 10 11 12 12 CoffeeScript Idioms 15 Each Map Select Includes Property Iteration Min/Max Multiple Arguments And/Or 15 15 16 17 17 17 18 18 iii Destructuring Assignments External Libraries Private Variables 19 19 19 Compiling CoffeeScript 21 Cake Creating Applications Structure and CommonJS Stitch It Up JavaScript Templates Bonus: 30-Second Deployment with Heroku Additional Libraries 21 23 23 24 26 28 29 The Good Parts 31 The Unfixed parts Using eval Using typeof Using instanceof Using delete Using parseInt Strict Mode Strict Mode Changes Strict Mode Usage The Fixed Parts A JavaScript Subset Global Variables Semicolons Reserved Words Equality Comparisons Function Definition Number Property Lookups JavaScript Lint 31 31 32 34 34 35 35 35 36 37 37 38 39 39 40 41 41 42 The Little Conclusion 43 Philosophy It’s Just JavaScript Build Your Own JavaScript iv | Table of Contents 43 44 45 Preface What Is CoffeeScript? CoffeeScript is a little language that compiles down to JavaScript The syntax is inspired by Ruby and Python, and implements many features from those two languages This book is designed to help you learn CoffeeScript, understand best practices, and start building awesome client-side applications The book is little, only six chapters, but that’s rather apt as CoffeeScript is a little language too This book is completely open source, and was written by Alex MacCaw (@maccman) with great contributions from David Griffiths, Satoshi Murakami, Chris Smith, Katsuya Noguchi, and Jeremy Ashkenas If you have any errata or suggestions, please don’t hesitate to open a ticket on the book’s GitHub page Readers may also be interested in JavaScript Web Applications (O’Reilly), a book I authored that explores rich JavaScript applications and moving state to the client side So let’s dive right into it: why is CoffeeScript better than writing pure JavaScript? Well, for a start, there’s less code to write; CoffeeScript is very succinct, and takes white space into account In my experience, this reduces code by a third to a half of the original pure JavaScript In addition, CoffeeScript has some neat features, such as array comprehensions, prototype aliases, and classes that further reduce the amount of typing you need to More importantly though, JavaScript has a lot of skeletons in its closet which can often trip up inexperienced developers CoffeeScript neatly sidesteps these by only exposing a curated selection of JavaScript features, fixing many of the language’s oddities CoffeeScript is not a superset of JavaScript, so although you can use external JavaScript libraries from inside CoffeeScript, you’ll get syntax errors if you compile JavaScript as is, without converting it The compiler converts CoffeeScript code into its counterpart JavaScript, there’s no interpretation at runtime So let’s get some common fallacies out of the way You will need to know JavaScript in order to write CoffeeScript, as runtime errors require JavaScript knowledge v However, having said that, runtime errors are usually pretty obvious, and so far I haven’t found mapping JavaScript back to CoffeeScript to be an issue The second problem I’ve often heard associated with CoffeeScript is speed (i.e., the code produced by the CoffeeScript compiler would run slower than its equivalent written in pure JavaScript) In practice though, it turns out this isn’t a problem either CoffeeScript tends to run as fast or faster than handwritten JavaScript What are the disadvantages of using CoffeeScript? Well, it introduces another compile step between you and your JavaScript CoffeeScript tries to mitigate the issue as best it can by producing clean and readable JavaScript, and with its server integrations which automate compilation The other disadvantage, as with any new language, is the fact that the community is still small at this point, and you’ll have a hard time finding fellow collaborators who already know the language CoffeeScript is quickly gaining momentum though, and its IRC list is well staffed; any questions you have are usually answered promptly CoffeeScript is not limited to the browser, and can be used to great effect in server-side JavaScript implementations, such as Node.js Additionally, CoffeeScript is getting much wider use and integration, such as being a default in Rails 3.1 Now is definitely the time to jump on the CoffeeScript train The time you invest in learning about the language now will be repaid by major time savings later Initial Setup One of the easiest ways to initially play around with the library is to use it right inside the browser Navigate to http://coffeescript.org and click on the Try CoffeeScript tab The site uses a browser version of the CoffeeScript compiler, converting any CoffeeScript typed inside the left panel to JavaScript in the right panel You can also convert JavaScript back to CoffeeScript using the js2coffee project, especially useful when migrating JavaScript projects to CoffeeScript In fact, you can use the browser-based CoffeeScript compiler yourself, by including this script in a page, marking up any CoffeeScript script tags with the correct type: # Some CoffeeScript Obviously, in production, you don’t want to be interpreting CoffeeScript at runtime, as it’ll slow things up for your clients Instead, CoffeeScript offers a Node.js compiler to pre-process CoffeeScript files vi | Preface To install it, first make sure you have a working copy of the latest stable version of Node.js and npm (the Node Package Manager) You can then install CoffeeScript with npm: npm install -g coffee-script The -g flag is important, as it tells npm to install the coffee-script package globally, rather than locally Without it, you won’t get the coffee executable If you execute the coffee executable without any command line options, it’ll give you the CoffeeScript console, which you can use to quickly execute CoffeeScript statements To pre-process files, pass the compile option: coffee compile my-script.coffee If output is not specified, CoffeeScript will write to a JavaScript file with the same name, in this case my-script.js This will overwrite any existing files, so be careful you’re not overwriting any JavaScript files unintentionally For a full list of the command line options available, pass help You can also pass the compile option a directory, and CoffeeScript will recursively compile every file with a coffee extension: coffee output lib compile src If all this compilation seems like a bit of an inconvenience and bother, that’s because it is We’ll be getting onto ways to solve this by automatically compiling CoffeeScript files, but first let’s take a look at the language’s syntax Conventions Used in This Book The following typographical conventions are used in this book: Italic Indicates new terms, URLs, email addresses, filenames, and file extensions Constant width Used for program listings, as well as within paragraphs to refer to program elements such as variable or function names, databases, data types, environment variables, statements, and keywords Constant width bold Shows commands or other text that should be typed literally by the user Constant width italic Shows text that should be replaced with user-supplied values or by values determined by context Preface | vii This icon signifies a tip, suggestion, or general note This icon indicates a warning or caution Using Code Examples This book is here to help you get your job done In general, you may use the code in this book in your programs and documentation You not need to contact us for permission unless you’re reproducing a significant portion of the code For example, writing a program that uses several chunks of code from this book does not require permission Selling or distributing a CD-ROM of examples from O’Reilly books does require permission Answering a question by citing this book and quoting example code does not require permission Incorporating a significant amount of example code from this book into your product’s documentation does require permission We appreciate, but not require, attribution An attribution usually includes the title, author, publisher, and ISBN For example: “The Little Book on CoffeeScript by Alex MacCaw (O’Reilly) Copyright 2012 Alex MacCaw, 978-1-449-32105-5.” If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com Safari® Books Online Safari Books Online is an on-demand digital library that lets you easily search over 7,500 technology and creative reference books and videos to find the answers you need quickly With a subscription, you can read any page and watch any video from our library online Read books on your cell phone and mobile devices Access new titles before they are available for print, and get exclusive access to manuscripts in development and post feedback for the authors Copy and paste code samples, organize your favorites, download chapters, bookmark key sections, create notes, print out pages, and benefit from tons of other time-saving features O’Reilly Media has uploaded this book to the Safari Books Online service To have full digital access to this book and others on similar topics from O’Reilly and other publishers, sign up for free at http://my.safaribooksonline.com viii | Preface example, let’s say we’re pushing a value onto an array We could say that, as long as the “array like” object implements push(), we should treat it like an array: anArray?.push? aValue If anArray is an object other than an array, then the existential operator will ensure that push() is never called Using instanceof JavaScript’s instanceof keyword is nearly as broken as typeof Ideally, instanceof would compare the constructor of two objects, returning a boolean if one was an instance of the other However, in reality, instanceof only works when comparing custom-made objects When it comes to comparing built-in types, it’s as useless as typeof: new String("foo") instanceof String # true "foo" instanceof String # false Additionally, instanceof also doesn’t work when comparing objects from different frames in the browser In fact, instanceof only returns a correct result for custom made objects, such as CoffeeScript classes: class Parent class Child extends Parent child = new Child child instanceof Child # true child instanceof Parent # true Make sure you only use it for your own objects or, even better, stay clear of it Using delete The delete keyword can only safely be used for removing properties inside objects: anObject = {one: 1, two: 2} delete anObject.one anObject.hasOwnProperty("one") # false Any other use, such as deleting variables or function’s won’t work: aVar = delete aVar typeof aVar # "integer" It’s rather peculiar behavior, but there you have it If you want to remove a reference to a variable, just assign it to null instead: aVar = aVar = null 34 | Chapter 5: The Good Parts Using parseInt JavaScript’s parseInt() function can return unexpected results if you pass a string to it without informing it of the proper base For example: # Returns 8, not 10! parseInt('010') is Always pass a base to the function to make it work correctly: # Use base 10 for the correct result parseInt('010', 10) is 10 This isn’t something CoffeeScript can for you; you’ll just have to remember to always specify a base when using parseInt() Strict Mode Strict mode is a new feature of ECMAScript that allows you to run a JavaScript program or function in a strict context This strict context throws more exceptions and warnings than the normal context, giving developers some indication when they’re straying from best practices, writing un-optimizable code or making common mistakes In other words, strict mode reduces bugs, increases security, improves performance, and eliminates some difficult-to-use language features What’s not to like? Strict mode is currently supported in the following browsers: • • • • • Chrome >= 13.0 Safari >= 5.0 Opera >= 12.0 Firefox >= 4.0 Internet Explorer >= 10.0 Having said that, strict mode is completely backwards compatible with older browsers Programs using it should run fine in either a strict or normal context Strict Mode Changes Most of the changes strict mode introduces pertain to JavaScript’s syntax: • Errors on duplicate property and function argument names • Errors on incorrect use of the delete operator • Access to arguments.caller & arguments.callee throws an error (for performance reasons) • Using the with operator will raise a syntax error • Certain variables such as undefined are no longer writeable The Unfixed parts | 35 • Introduces additional reserved keywords, such as implements, interface, let, package, private, protected, public, static, and yield However, strict mode also changes some runtime behavior: • Global variables are explicit (var always required); the global value of this is undefined • eval can’t introduce new variables into the local context • Function statements have to be defined before they’re used (previously, functions could be defined anywhere) • arguments is immutable CoffeeScript already abides by a lot of strict mode’s requirements, such as always using var when defining variables, but it’s still very useful to enable strict mode in your CoffeeScript programs Indeed, CoffeeScript is taking this a step further, and in future versions will check a program’s compliance to strict mode at compile time Strict Mode Usage All you need to to enable strict checking is start your script or function with the following string: -> "use strict" # your code That’s it, just the "use strict" string Couldn’t be simpler and it’s completely backwards compatible Let’s take a look at strict mode in action The following function will raise a syntax error in strict mode, but run fine in the usual mode: -> "use strict" console.log(arguments.callee) Strict mode has removed access to arguments.caller and arguments.callee, as they’re major performance hogs, and is now throwing syntax errors whenever they’re used There’s a particular gotcha you should look out for when using strict mode, namely creating global variables with this The following example will throw a TypeError in strict mode, but run fine in a normal context, creating a global variable: -> "use strict" class @Spine The reason behind this disparity is that in strict mode, this is undefined, whereas normally it refers to the window object The solution to this is to explicitly set global variables on the window object: 36 | Chapter 5: The Good Parts -> "use strict" class window.Spine While I recommend enabling strict mode, it’s worth noting that script mode doesn’t enable any new features that aren’t already possible in JavaScript, and will actually slow down your code a bit by having the VM more checks at runtime You may want to develop with strict mode, and deploy to production without it The Fixed Parts Now that we’ve covered some of JavaScript’s warts that CoffeeScript can’t fix, let’s talk about a few that CoffeeScript does fix In my mind, the following features are some of the best reasons to use CoffeeScript; they fix some of the most common mistakes developers make when writing JavaScript While this is more of an academic discussion, you should still find the rest of this chapter useful, especially when making the case to use CoffeeScript! A JavaScript Subset CoffeeScript’s syntax only covers a subset of JavaScript’s, the famous Good Parts, so already there’s less to fix Let’s take the with statement for example This statement has for a long time been “considered harmful,” and should be avoided with was intended to provide a shorthand for writing recurring property lookups on objects For example, instead of writing: dataObj.users.alex.email = "info@eribium.org"; You could write: with(dataObj.users.alex) { email = "info@eribium.org"; } Setting aside the fact that we shouldn’t have such a deep object in the first place, the syntax is quite clean Except for one thing It’s confusing to the JavaScript interpreter, which doesn’t know exactly what you’re going to in the with context, and forces the specified object to be searched first for all name lookups This really hurts performance and means the interpreter has to turn off all sorts of JIT optimizations Additionally, with statements can’t be minified using tools like uglify-js They’re also deprecated and removed from future JavaScript versions All things considered, it’s much better just to avoid using them, and CoffeeScript takes this a step further by eliminating them from its syntax In other words, using with in CoffeeScript will throw a syntax error The Fixed Parts | 37 Global Variables By default, your JavaScript programs run in a global scope, and by default, any variables created are in that global scope If you want to create a variable in the local scope, JavaScript requires explicitly indicating that fact using the var keyword usersCount = 1; var groupsCount = 2; // Global // Global (function(){ pagesCount = 3; var postsCount = 4; })() // Global // Local This is a bit of an odd decision since the vast majority of the time you’ll be creating local variables not global ones, so why not make that the default? As it stands, developers have to remember to put var statements before any variables they’re initializing, or face weird bugs when variables accidentally conflict and overwrite each other Luckily, CoffeeScript comes to your rescue here by eliminating implicit global variable assignment entirely In other words, the var keyword is reserved in CoffeeScript, and will trigger a syntax error if used Local variables are created implicitly by default, and it’s very difficult to create global variables without explicitly assigning them as properties on window Let’s have a look at an example of CoffeeScript’s variable assignment: outerScope = true -> innerScope = true Compiles down to: var outerScope; outerScope = true; (function() { var innerScope; return innerScope = true; })(); Notice how CoffeeScript initializes variables (using var) automatically in the context they are first used While CoffeeScript makes it difficult to shadow outer variables, you can still refer to and access them You need to watch out for this; be careful that you’re not reusing the name of an external variable accidentally if you’re writing a deeply nested function or class For example, here we’re accidentally overwriting the package variable in a Class function: package = require('./package') class Hem build: -> # Overwrites outer variable! package = @hemPackage.compile() 38 | Chapter 5: The Good Parts hemPackage: -> package.create() Global variables are needed from time to time, and to create those you need to set them as properties on window: class window.Asset constructor: -> By ensuring global variables are explicit, rather than implicit, CoffeeScript removes one of the major sources of bugs in JavaScript programs Semicolons JavaScript does not enforce the use of semicolons in source code, so it’s possible to omit them However, behind the scenes, the JavaScript compiler still needs them, so the parser automatically inserts them whenever it encounters a parse error due to a missing semicolon In other words, it’ll try to evaluate a statement without semicolons and, if that fails, tries again using semicolons Unfortunately, this is a tremendously bad idea, and can actually change the behavior of your code Take the following example, which seems like valid JavaScript, right? function() {} (window.options || {}).property Wrong Well, at least according to the parser; it raises a syntax error In case of a leading parenthesis, the parser will not insert a semicolon The code gets transformed onto one line: function() {}(window.options || {}).property Now you can see the issue, and why the parser is complaining When you’re writing JavaScript, you should always include semicolons after statements Fortunately, CoffeeScript gets around all this hassle by not having semicolons in its syntax Rather, the semicolons are inserted automatically (at the right places) when the CoffeeScript is compiled down to JavaScript Reserved Words Certain keywords in JavaScript are reserved for future versions of JavaScript, such as const, enum, and class Using these as variable names in your JavaScript programs can result in unpredictable results; some browsers will cope with them just fine, and others will choke CoffeeScript neatly sidesteps this issue, by detecting if you’re using a reserved keyword, and escaping it if necessary For example, let’s say you were to use the reserved keyword class as a property on an object Your CoffeeScript might look like this: myObj = { delete: "I am a keyword!" The Fixed Parts | 39 } myObj.class = -> The CoffeeScript parser notices you’re using a reserved keyword, and quotes it for you: var myObj; myObj = { "delete": "I am a keyword!" }; myObj["class"] = function() {}; Equality Comparisons The weak equality comparison in JavaScript has some confusing behavior and is often the source of confusing bugs The example below is taken from JavaScript Garden’s equality section, which delves into the issue in some depth: "" 0 false false false false null " \t\r\n" == == == == == == == == == "0" "" "0" "false" "0" undefined null undefined // // // // // // // // // false true true false true false false true true The reason behind this behavior is that the weak equality coerces types automatically I’m sure you’ll agree this is all pretty ambiguous, and can lead to unexpected results and bugs The solution is to instead use the strict equality operator, which consists of three equal signs (===) It works exactly like the normal equality operator, but without any type coercion It’s recommended to always use the strict equality operator, and explicitly convert types if needs be CoffeeScript solves this by simply replacing all weak comparisons with strict ones (in other words, converting all == comparators into ===) You can’t a a weak equality comparison in CoffeeScript, and you should explicitly convert types before comparing them if necessary This doesn’t mean you can ignore type coercion in CoffeeScript completely though, especially when it comes to checking the “truthfulness” of variables during flow control Blank strings, null, undefined, and the number are all coerced to false: alert("Empty Array") unless [].length alert("Empty String") unless "" alert("Number 0") unless If you want to explicitly check for null and undefined, then you can use CoffeeScript’s existential operator: alert("This is not called") unless ""? 40 | Chapter 5: The Good Parts The alert() in this example won’t be called, as the empty string isn’t equal to null Function Definition Oddly enough, in JavaScript, functions can be defined after they’re used For example, the following runs absolutely fine, even though wem is defined after it’s called: wem(); function wem() {} This is because of function scope Functions get hoisted before the program’s execution and as such are available everywhere in the scope they were defined in, even if called before the actual definition in the source The trouble is, hoisting behavior differs between browser For example: if (true) { function declaration() { return "first"; } } else { function declaration() { return "second"; } } declaration(); In some browsers (e.g., Firefox), declaration() will return "first", and in other browsers (e.g., Chrome), it’ll return "second", even though it looks like the else statement is never run If you want to know more about declarative functions, then you should read Juriy Zaytsev’s guide, where he delves into the specifics Suffice to say, they have fairly ambiguous behavior, and can lead to problems later down the road All things considered, it’s best to steer clear of them by using function expressions instead: var wem = function(){}; wem(); CoffeeScript’s approach to this is to remove declarative functions entirely, using function expressions instead Number Property Lookups A flaw in JavaScript’s parser means that the dot notation on numbers is interpreted as a floating point literal, rather than a property lookup For example, the following JavaScript will cause a syntax error: 5.toString(); JavaScript’s parser is looking for another number after the dot, and so raises an Unexpected token error when it encounters toString() The solution to this is to either use parenthesis, or add an additional dot: The Fixed Parts | 41 (5).toString(); toString(); Fortunately, CoffeeScript’s parsers are clever enough to deal with this issue by using double dot notations automatically (as in the preceding example) whenever you access properties on numbers JavaScript Lint JavaScript Lint is a JavaScript code quality tool, and running your programs through it is a great way of improving code quality and best practices The project was based on a similar tool called JSLint Check out JSLint’s site for a great list of issues that it checks for, including global variables, missing semicolons, and weak equality comparisons The good news is that CoffeeScript already “lints” all of its output, so CoffeeScript generated JavaScript is already JavaScript Lint compatible In fact, the coffee tool has support for a lint option: coffee lint index.coffee index.coffee: error(s), warning(s) 42 | Chapter 5: The Good Parts CHAPTER The Little Conclusion By Jeremy Ashkenas1 You’ve reached the end of The Little Book on CoffeeScript, and now you know just about everything you’ll need CoffeeScript is a little language at heart, and if you know JavaScript and have a sense of the philosophy behind the changes that CoffeeScript makes to JavaScript, you should be able to get up and running very quickly indeed Philosophy Unlike most programming languages, CoffeeScript was never designed from the ground up It has always been an attempt to express core JavaScript concepts in as simple and minimal a syntax as we can find for them Let’s take a simple function To produce the square of x, we multiply x by itself In JavaScript: var square = function(x) { return x * x; }; To derive the CoffeeScript for this, let’s think through the steps it would take to reduce this function to its essential features • We can understand the code perfectly well without the semicolons, so let’s drop those • Instead of using { and } to delimit the body of the function, let’s use the indentation that’s already present on the page • It’s clear that we’re defining a new function, so let’s drop the redundant var in front of the assignment This last chapter was kindly contributed by Jeremy Ashkenas, the author of CoffeeScript 43 • Every construct in CoffeeScript should be an expression with a value, so the natural value of a function body is the last line of code it executes allowing us to omit the return • Finally, we replace function( input ){ output } with a function literal that visually represents the idea that the input of a function “points to” the output: (input) -> output Voilá, the CoffeeScript version: square = (x) -> x * x Every language feature in CoffeeScript has been designed using this kind of process: attempt to take the beautiful dynamic semantics of JavaScript—object literals, function expressions, prototypal inheritance—and express them in a clean, readable, minimal way It’s Just JavaScript CoffeeScript tries to be a deeply pragmatic language To be honest, it’s probably too pragmatic for its own good The golden rule of CoffeeScript is: “It’s just JavaScript.” We want to embrace the limitations of compiling to JavaScript by only implementing things that can be expressed in simple JS, and leaving fancier compilations to other languages When you run a script, there is no CoffeeScript interpreter running within the browser, no core library you have to include on the page, and ideally (although we bend this rule in a few places) no special helper functions generated alongside your code The downside of this approach is that more invasive improvements to JavaScript are impossible For example, it would be nice if list[-1] in CoffeeScript could return the last item in the list At first glance, it seems simple enough to implement, and would be useful Unfortunately, any expression may be used to index into an array, so with negative array indices you would have to add a special check to every list[x] operation to ask if x is a positive number or a negative one This would take CoffeeScript away from JavaScript semantics, and more importantly, JavaScript levels of performance—the array accesses in your inner loops would slow down considerably For this reason, CoffeeScript doesn’t add negative array indices to the language The upside of this approach is that CoffeeScript is inherently compatible with every JavaScript runtime Because we can compile to efficient, lowest-common-denominator code, CoffeeScript runs as well as JavaScript in every browser, in Node.js, in Rhino, in Photoshop and Illustrator—in short, everywhere JavaScript can run If you want to use CoffeeScript for a project, for a component, or even just for a single file, you don’t have to sacrifice performance or compatibility with other JavaScript libraries 44 | Chapter 6: The Little Conclusion Build Your Own JavaScript There’s a hidden motive running as a subtext beneath CoffeeScript I hope that this book doesn’t merely serve as an introduction, but spurs you to experiment with compile-to-JavaScript languages of your very own To that end, the CoffeeScript compiler has been fully annotated with commentary to make it easier to get started prototyping changes and improvements The entire thing is only around 2,500 lines of code, and there have been a number of interesting forks already that push JavaScript in different directions If you’ve ever felt confined by JavaScript, there’s no need to wait around for browser implementors or the slow march of the standards process By using a compile-to-JS language, you can give yourself the JavaScript of your dreams today I’m looking forward to seeing more little languages out there in the wild soon Build Your Own JavaScript | 45 About the Author Alex MacCaw is a Ruby/JavaScript developer and entrepreneur He has written a JavaScript framework, Spine, and developed major applications including Taskforce and Socialmod, as well as a host of open source work He has spoken at Ruby/Rails conferences in New York City, San Francisco, and Berlin In addition to programming, he is currently traveling around the world with a Nikon D90 and surfboard ... helpers to manage this One such helper is a variation on ->, the fat arrow function: => Using the fat arrow instead of the thin arrow ensures that the function context will be bound to the local one... coercion is a bit odd, and its equality operator coerces types in order to compare them, leading to some confusing behaviors and the source of many bugs There’s a longer discussion on this topic... if @logPrefix console?.log(args ) Bear in mind though that CoffeeScript will automatically set the function invocation context to the object the function is being invoked on In the example above,

Ngày đăng: 04/03/2019, 13:39

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN