Oh My JS The Best JavaScript Articles Azat Mardan Thisbookisforsaleathttp://leanpub.com/ohmyjs Thisversionwaspublishedon2014-05-28 ThisisaLeanpubbook.LeanpubempowersauthorsandpublisherswiththeLeanPublishing process.LeanPublishingistheactofpublishinganin-progressebookusinglightweighttoolsand manyiterationstogetreaderfeedback,pivotuntilyouhavetherightbookandbuildtractiononce youdo. ©2013-2014AzatMardan Tweet This Book! PleasehelpAzatMardanbyspreadingthewordaboutthisbookonTwitter! Thesuggestedtweetforthisbookis: IjustboughtOhMyJSCC@RPJSBook Thesuggestedhashtagforthisbookis#ohmyjs. Findoutwhatotherpeoplearesayingaboutthebookbyclickingonthislinktosearchforthis hashtagonTwitter: https://twitter.com/search?q=#ohmyjs Also By Azat Mardan RapidPrototypingwithJS Express.jsGuide JavaScriptandNodeFUNdamentals ToGod,MyTeachersandVladimirNabokov Contents JavaScriptFundamentals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 TheWorld’sMostMisunderstoodProgrammingLanguage . . . . . . . . . . . . . . . . . . 1 UnderstandingJavaScriptFunctionInvocationand“this” . . . . . . . . . . . . . . . . . . 4 CodeConventionsfortheJavaScriptProgrammingLanguage . . . . . . . . . . . . . . . . 9 SemicolonsinJavaScriptareoptional . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 PatternsandCodeOrganization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 CommonJavaScript“Gotchas” . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 AsynchronousJS:Callbacks,Listeners,ControlFlowLibsandPromises. . . . . . . . . . . 35 TheDesignofCode:OrganizingJavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . 44 WhyAMD? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 JavaScriptDependencyInjection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 10MustHaveJavaScriptToolsForDevelopers . . . . . . . . . . . . . . . . . . . . . . . . 66 UsefulNode.jsTools,TutorialsAndResources . . . . . . . . . . . . . . . . . . . . . . . . 76 ControltheComplexityofYourJavaScriptFunctionswithJSHint . . . . . . . . . . . . . . 83 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Leaner,Meaner,FasterAnimationswithrequestAnimationFrame . . . . . . . . . . . . . . 87 Node.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 UnderstandingeventloopsandwritinggreatcodeforNode.js . . . . . . . . . . . . . . . . 98 CallbackHell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101 UnderstandingExpress.js . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 AbouttheAuthor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 JavaScript Fundamentals The World’s Most Misunderstood Programming Language Original Article http://javascript.crockford.com/javascript.html DouglasCrockford,crockford.com http://crockford.com .. JavaScript¹, aka Mocha, aka LiveScript, aka JScript, aka ECMAScript, is one of the world’s most popular programming languages. Virtually every personal computer in the world has at least one JavaScript interpreter installed on it and in active use. JavaScript’s popularity is due entirely to its roleasthescriptinglanguageoftheWWW. Despite its popularity, few know that JavaScript is a very nice dynamic object-oriented general- purposeprogramminglanguage.Howcanthisbeasecret?Whyisthislanguagesomisunderstood? The Name The Java- prefix suggests that JavaScript is somehow related to Java, that it is a subset or less capable version of Java. It seems that the name was intentionally selected to create confusion, and fromconfusioncomesmisunderstanding.JavaScriptisnotinterpretedJava.JavaisinterpretedJava. JavaScriptisadifferentlanguage. JavaScripthasasyntacticsimilaritytoJava,muchasJavahastoC.ButitisnomoreasubsetofJava thanJavaisasubsetofC.ItisbetterthanJavaintheapplicationsthatJava(fkaOak)wasoriginally intendedfor. JavaScript was not developed at Sun Microsystems, the home of Java. JavaScript was developed at Netscape.ItwasoriginallycalledLiveScript,butthatnamewasn’tconfusingenough. The -Script suffix suggests that it is not a real programming language, that a scripting language is less than a programming language. But it is really a matter of specialization. Compared to C, JavaScripttradesperformanceforexpressivepoweranddynamism. ¹http://javascript.crockford.com/ JavaScriptFundamentals 2 Lisp in C’s Clothing JavaScript’s C-like syntax, including curly braces and the clunky for statement, makes it appear to be an ordinary procedural language. This is misleading because JavaScript has more in common withfunctionallanguageslikeLisporScheme²thanwithCorJava.Ithasarraysinsteadoflistsand objects instead of property lists. Functions are first class. It has closures. You get lambdas without havingtobalanceallthoseparens. Typecasting JavaScriptwasdesignedtoruninNetscapeNavigator.Itssuccessthereledtoitbecomingstandard equipment in virtually all web browsers. This has resulted in typecasting. JavaScript is the George Reeves³ of programming languages. JavaScript is well suited to a large class of non-Web-related applications Moving Target The first versions of JavaScript were quite weak. They lacked exception handling, inner functions, and inheritance. In its present form, it is now a complete object-oriented programming language. Butmanyopinionsofthelanguagearebasedonitsimmatureforms. TheECMAcommitteethathasstewardshipoverthelanguageisdevelopingextensionswhich,while wellintentioned,willaggravateoneofthelanguage’sbiggestproblems:Therearealreadytoomany versions.Thiscreatesconfusion. Design Errors No programming language is perfect. JavaScript has its share of design errors, such as the overloading of + to mean both addition and concatenation with type coercion, and the error- pronewithstatementshouldbeavoided.Thereservedwordpoliciesaremuchtoostrict.Semicolon insertion was a huge mistake, as was the notation for literal regular expressions. These mistakes have led to programming errors, and called the design of the language as a whole into question. Fortunately,manyoftheseproblemscanbemitigatedwithagoodlint⁴program. The design of the language on the whole is quite sound. Surprisingly, the ECMAScript committee does not appear to be interested in correcting these problems. Perhaps they are more interested in makingnewones. ²http://javascript.crockford.com/little.html ³http://www.amazon.com/exec/obidos/ASIN/B000KWZ7JC/wrrrldwideweb ⁴http://www.jslint.com/ JavaScriptFundamentals 3 Lousy Implementations Some of the earlier implementations of JavaScript were quite buggy. This reflected badly on the language. Compounding that, those implementations were embedded in horribly buggy web browsers. Bad Books Nearly all of the books about JavaScript are quite awful. They contain errors, poor examples, and promote bad practices. Important features of the language are often explained poorly, or left out entirely. I have reviewed dozens of JavaScript books, andI can only recommend one: JavaScript: The Definitive Guide (5th Edition)⁵ by David Flanagan. (Attention authors: If you have written a goodone,pleasesendmeareviewcopy.) Substandard Standard Theofficialspecificationforthelanguage⁶ispublishedbyECMA⁷.Thespecificationisofextremely poorquality.Itisdifficulttoreadandverydifficulttounderstand.Thishasbeenacontributortothe BadBookproblembecauseauthorshavebeenunabletousethestandarddocumenttoimprovetheir ownunderstandingofthelanguage.ECMAandtheTC39committeeshouldbedeeplyembarrassed. Amateurs MostofthepeoplewritinginJavaScriptarenotprogrammers.Theylackthetraininganddiscipline to write good programs. JavaScript has so much expressive power that they are able to do useful things in it, anyway. This has given JavaScript a reputation of being strictly for the amateurs, that itisnotsuitableforprofessionalprogramming.Thisissimplynotthecase. Object-Oriented IsJavaScriptobject-oriented?Ithasobjectswhichcancontaindataandmethodsthatactuponthat data.Objectscancontainotherobjects.Itdoesnothaveclasses,butitdoeshaveconstructorswhich dowhatclassesdo,includingactingascontainersforclassvariablesandmethods.Itdoesnothave class-orientedinheritance,butitdoeshaveprototype-orientedinheritance. Thetwomainwaysofbuildingupobjectsystemsarebyinheritance(is-a)andbyaggregation(has- a).JavaScriptdoesboth,butitsdynamicnatureallowsittoexcelataggregation. Some argue that JavaScript is not truly object oriented because it does not provide information hiding.Thatis,objectscannothaveprivatevariablesandprivatemethods:Allmembersarepublic. ⁵http://www.amazon.com/exec/obidos/ASIN/0596101996/wrrrldwideweb ⁶http://www.ecma-international.org/publications/standards/Ecma-262.htm ⁷http://www.ecma-international.org/ JavaScriptFundamentals 4 But it turns out that JavaScript objects can have private variables and private methods. (Click here now to find out how.)⁸ Of course, few understand this because JavaScript is the world’s most misunderstoodprogramminglanguage. SomearguethatJavaScript isnot truly objectorientedbecauseit does notprovideinheritance.But it turns out that JavaScript supports not only classical inheritance, but other code reuse patterns as well.⁹ Copyright2001DouglasCrockford.¹⁰AllRightsReservedWrrrldwide.¹¹ Understanding JavaScript Function Invocation and “this” Original Article http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this YehudaKatz,yehudakatz.com .. Overtheyears,I’veseenalotofconfusionaboutJavaScriptfunctioninvocation.Inparticular,alot ofpeoplehavecomplainedthatthesemanticsof thisinfunctioninvocationsisconfusing. In my opinion, a lot of this confusion is cleared up by understanding the core function invocation primitive,andthenlookingatallotherwaysofinvokingafunctionassugarontopofthatprimitive. In fact, this is exactly how the ECMAScript spec thinks about it. In some areas, this post is a simplificationofthespec,butthebasicideaisthesame. The Core Primitive First, let’s look at the core function invocation primitive, a Function’s call method[1]. The call methodisrelativelystraightforward. 1. Makeanargumentlist(argList)outofparameters1throughtheend 2. ThefirstparameteristhisValue 3. InvokethefunctionwiththissettothisValueandtheargListasitsargumentlist Forexample: ⁸http://www.crockford.com/javascript/private.html ⁹http://javascript.crockford.com/inheritance.html ¹⁰mailto:[email protected] ¹¹http://www.crockford.com/
Description: