




























































































Estude fácil! Tem muito documento disponível na Docsity
Ganhe pontos ajudando outros esrudantes ou compre um plano Premium
Esta página não é visível na pré-visualização
Não perca as partes importantes!





























































































From arguments to function parameters 47 ■^ Invocation as a function 49 ■^ Invocation as a method 50 ■^ Invocation as
CONTENTS vii
xii PREFACE
Perhaps the largest change that came to jQuery as a result of writing this book was a complete overhaul from using browser-specific sniffing to using feature detection at the core of the library. This has enabled jQuery to be used almost indefinitely, without assuming that browsers would always have specific bugs or be missing specific features. As a result of these changes, jQuery anticipated many of the improvements to brows- ers that have come during the past couple years: Google released the Chrome browser; the number of user agents has exploded as mobile computing has increased in popu- larity; Mozilla, Google, and Apple have gotten into a browser performance war; and Microsoft has finally started making substantial improvements to Internet Explorer. It can no longer be assumed that a single rendering engine (such as WebKit, or Trident in Internet Explorer) will always behave the same way. Substantial changes are occurring rapidly and are spread out to an ever-increasing number of users. Using the techniques outlined in this book, jQuery’s cross-browser capabilities pro- vide a fairly solid guarantee that code written with jQuery will work in a maximum number of browser environments. This guarantee has led to explosive growth in jQuery over the past four years, with it now being used in over 57% of the top 10, websites on the Internet, according to BuiltWith.com. JavaScript’s relatively unchanging features, such as code evaluation, controversial with statements, and timers, are continually being used in interesting ways. There are now a number of active programming languages that are built on top of, or compiled to, JavaScript, such as CoffeeScript and Processing.js. These languages require com- plex language parsing, code evaluation, and scope manipulation in order to work effectively. Although dynamic code evaluation has been maligned due to its complex- ity and potential for security issues, without it we wouldn’t have had the CoffeeScript programming language, which has gone on to influence the upcoming ECMAScript specification itself. I’m personally making use of all of these features, even today, in my work at Khan Academy. Dynamic code evaluation in the browser is a very powerful feature: you can build in-browser programming environments and do crazy things like inject code into a live runtime. This results in an extremely compelling way to learn computer pro- gramming and provides new capabilities that wouldn’t be possible in a traditional learning environment. The future for browser development continues to be very strong, and it’s largely due to the features encapsulated in JavaScript and in the browser APIs. Having a solid grasp of the most crucial parts of the JavaScript language, combined with a desire for writing code that’ll work in many browsers, will enable you to create code that’s ele- gant, fast, and ubiquitous.
JOHN RESIG
xiii
acknowledgments
The number of people involved in writing a book would surprise most people. It took a collaborative effort on the part of many contributors with a variety of talents to bring the volume you are holding (or ebook that you are reading onscreen) to fruition. The staff at Manning worked tirelessly with us to make sure this book attained the level of quality we hoped for, and we thank them for their efforts. Without them, this book would not have been possible. The “end credits” for this book include not only our publisher, Marjan Bace, and editor Mike Stephens, but also the following contribu- tors: Jeff Bleiel, Douglas Pudnick, Sebastian Stirling, Andrea Kaucher, Karen Tegtmayer, Katie Tennant, Megan Yockey, Dottie Marsico, Mary Piergies, Andy Carroll, Melody Dolab, Tiffany Taylor, Dennis Dalinnik, Gabriel Dobrescu, and Ron Tomich. Enough cannot be said to thank our peer reviewers who helped mold the final form of the book, from catching simple typos to correcting errors in terminology and code, and helping to organize the chapters in the book. Each pass through a review cycle ended up vastly improving the final product. For taking the time to review the book, we’d like to thank Alessandro Gallo, André Roberge, Austin King, Austin Ziegler, Chad Davis, Charles E. Logston, Chris Gray, Christopher Haupt, Craig Lancaster, Curtis Miller, Daniel Bretoi, David Vedder, Erik Arvidsson, Glenn Stokol, Greg Donald, James Hatheway, Jared Hirsch, Jim Roos, Joe Litton, Johannes Link, John Paulson, Joshua Heyer, Julio Guijarro, Kurt Jung, Loïc Simon, Neil Mix, Robert Hanson, Scott Sauyet, Stuart Caborn, and Tony Niemann. Special thanks go to Valentin Crettaz, who served as the book’s technical editor. In addition to checking each and every sample of example code in multiple environments,
xv
about this book
JavaScript is important. That wasn’t always so, but it’s true now. Web applications are expected to give users a rich user interface experience, and without JavaScript, you might as well just be showing pictures of kittens. More than ever, web developers need to have a sound grasp of the language that brings life to web applications. And like orange juice and breakfast, JavaScript isn’t just for browsers anymore. The language has knocked down the walls of the browser and is being used on the server in engines such as Rhino and V8, and in frameworks like Node.js. Although this book is primarily focused on JavaScript for web applications, the fundamentals of the language presented in part 2 of this book are applicable across the board. With more and more developers using JavaScript, it’s now more important than ever that they grasp its fundamentals, so that they can become true ninjas of the language.
This is not your first JavaScript book. If you’re a complete novice to JavaScript, or you only understand a handful of statements by searching the web for code snippets, this is not the book for you. Yet. This book is aimed at web developers who already have at least a basic grasp of JavaScript. You should understand the basic structure of JavaScript statements and how they work to create straightforward on-page scripts. You don’t need to be an
xvi ABOUT THIS BOOK
advanced user of the language—that’s what this book is for—but you shouldn’t be a rank novice. You should also have a working knowledge of HTML and CSS. Again, nothing too advanced, but you should know the basics of putting a web page together. If you want some good prerequisite material, grab one of the popular books on JavaScript and web development, and then tackle this one. We can recommend JavaScript: The Definitive Guide by David Flanagan, JavaScript: The Good Parts by Douglas Crockford, and Head First JavaScript by Michael Morrison.
This book is organized to take you from an apprentice to a ninja in four parts. Part 1 introduces the topic and some tools we’ll need as we progress through the rest of the book. Part 2 focuses on JavaScript fundamentals: aspects of the language that you take for granted but aren’t really sure how they work. This may be the most important part of the book, and even if it’s all you read, you’ll come away with a much sounder under- standing of JavaScript, the language. In part 3, we dive into using the fundamentals that we learned in part 2 to solve knotty problems that the browsers throw at us. Part 4 wraps up the book with a look at advanced topics focusing on lessons learned from the creation of advanced JavaScript libraries, such as jQuery. Let’s take a brief look at what each chapter will cover. Chapter 1 introduces us to the challenges that we face as writers of advanced web applications. It presents some of the problems that the proliferation of browsers cre- ates, and suggests best current practices that we should follow when developing our applications, including testing and performance analysis. Chapter 2 discusses testing, taking a look at the current state of testing and test tools. It also introduces a small but powerful testing concept, the assert, which will be used extensively throughout the remainder of the book to make sure that our code does what we think it should be doing (or sometimes to prove that it doesn’t!). Armed with these tools, chapter 3 begins our foray into the fundamentals of the language, starting, perhaps to your surprise, with a thorough examination of the func- tion as defined by JavaScript. Although you might have expected the object to be the target of first focus, it’s a solid understanding of the function, and JavaScript as a func- tional language, that begins our transformation from run-of-the-mill JavaScript coders to JavaScript ninjas! Not being done with functions quite yet, chapter 4 takes the fundamentals we learned in chapter 3 and applies them to problems we face in creating our applica- tions. We’ll explore recursion—not only for its own sake, but because we can learn a lot more about functions through scrutinizing it—and we’ll learn how the functional programming aspects of JavaScript can be applied to not only make our code elegant, but also more robust and succinct. We’ll learn ways to deal with variable argument
xviii ABOUT THIS BOOK
browser-agnostic manner. This includes adding features not provided by the browsers, such as custom events and event delegation. In part 4 we pick up the pace and delve deeply into advanced topics taken from the heart of JavaScript libraries such as jQuery. Chapter 14 discusses how DOM manipula- tion API s can be constructed to manipulate the Document Object Model at runtime, including the Gordian knot of injecting new elements into the DOM. Finally, in chapter 15, we discuss how CSS selector engines are constructed and the different ways in which they parse and evaluate selectors. Not for the faint of heart, this chapter, but it’s a worthy final test of your ninja-hood.
All source code in listings or in the text is in a fixed-width font like this to sepa- rate it from ordinary text. Method and function names, properties, XML elements, and attributes in the text are also presented in this same font. In some cases, the original source code has been reformatted to fit on the pages. In general, the original code was written with page-width limitations in mind, but sometimes you may find a slight formatting difference between the code in the book and that provided in the source download. In a few rare cases, where long lines could not be reformatted without changing their meaning, the book listings contain line- continuation markers. Code annotations accompany many of the listings, highlighting important con- cepts. In many cases, numbered bullets link to explanations that follow in the text.
Source code for all the working examples in this book (along with some extras that never made it into the text) is available for download from the book’s web page at www.manning.com/SecretsoftheJavaScriptNinja. The code examples for this book are organized by chapter, with separate folders for each chapter. The layout is ready to be served by a local web server, such as the Apache HTTP Server. Simply unzip the downloaded code into a folder of your choice and make that folder the document root of the application. With a few exceptions, most of the examples don’t require the presence of a web server at all and can be loaded directly into a browser for execution, if you so desire. All examples were tested in a variety of modern browsers (as of mid-2012), includ- ing Internet Explorer 9, Firefox, Safari, and Google Chrome.
The authors and Manning Publications invite you to the book’s forum, run by Man- ning Publications, where you can make comments about the book, ask technical ques- tions, and receive help from the authors and other users. To access and subscribe to the forum, point your browser to www.manning.com/SecretsoftheJavaScriptNinja and click the Author Online link. This page provides information on how to get on the
ABOUT THIS BOOK xix
forum once you are registered, what kind of help is available, and the rules of conduct in the forum. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the authors can take place. It’s not a commitment to any specific amount of participation on the part of the authors, whose contribution to the book’s forum remains voluntary (and unpaid). We suggest you try asking the authors some challenging questions, lest their interest stray! The Author Online forum and the archives of previous discussions will be accessi- ble from the publisher’s website as long as the book is in print.
The figure on the cover of Secrets of the JavaScript Ninja is captioned “Noh Actor, Samurai,” from a woodblock print by an unknown Japanese artist of the mid-nineteenth century. Derived from the Japanese word for talent or skill , Noh is a form of classical Japanese musical drama that has been performed since the 14th century. Many char- acters are masked, with men playing male and female roles. The samurai, a hero fig- ure in Japan for hundreds of years, was often featured in the performances, and in this print the artist renders with great skill the beauty of the costume and the ferocity of the samurai. Samurai and ninjas were both warriors excelling in the Japanese art of war, known for their bravery and cunning. Samurai were elite soldiers, well-educated men who knew how to read and write as well as fight, and they were bound by a strict code of honor called Bushido (The Way of the Warrior), which was passed down orally from generation to generation, starting in the 10th century. Recruited from the aristocracy and upper classes, analagous to European knights, samurai went into battle in large formations, wearing elaborate armor and colorful dress meant to impress and intimi- date. Ninjas were chosen for their martial arts skills rather than their social standing or education. Dressed in black and with their faces covered, they were sent on mis- sions alone or in small groups to attack the enemy with subterfuge and stealth, using any tactics to assure success; their only code was one of secrecy. The cover illustration is from a set of three Japanes prints owned for many years by a Manning editor, and when we were looking for a ninja for the cover of this book, the striking samurai print came to our attention and was selected for its intricate details, vibrant colors, and vivid depiction of a ferocious warrior ready to strike—and win. At a time when it is hard to tell one computer book from another, Manning cele- brates the inventiveness and initiative of the computer business with book covers based on two-hundred-year-old illustrations that depict the rich diversity of traditional costumes from around the world, brought back to life by prints such as this one.