secrets of the javascript ninja

394 880 0
secrets of the javascript ninja

Đ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

www.it-ebooks.info Secrets of the JavaScript Ninja JOHN RESIG BEAR BIBEAULT MANNING S HELTER I SLAND www.it-ebooks.info For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 261 Shelter Island, NY 11964 Email: orders@manning.com ©2013 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editors: Jeff Bleiel, Sebastian Stirling 20 Baldwin Road Technical editor: Valentin Crettaz PO Box 261 Copyeditor: Andy Carroll Shelter Island, NY 11964 Proofreader: Melody Dolab Typesetter: Dennis Dalinnik Cover designer: Leslie Haimes ISBN: 978-1-933988-69-6 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 18 17 16 15 14 13 12 www.it-ebooks.info iii brief contents P ART 1 P REPARING FOR TRAINING . 1 1 ■ Enter the ninja 3 2 ■ Arming with testing and debugging 13 P ART 2 A PPRENTICE TRAINING 29 3 ■ Functions are fundamental 31 4 ■ Wielding functions 61 5 ■ Closing in on closures 89 6 ■ Object-orientation with prototypes 119 7 ■ Wrangling regular expressions 151 8 ■ Taming threads and timers 175 P ART 3 N INJA TRAINING 191 9 ■ Ninja alchemy: runtime code evaluation 193 10 ■ With statements 215 11 ■ Developing cross-browser strategies 229 12 ■ Cutting through attributes, properties, and CSS 253 www.it-ebooks.info BRIEF CONTENTS iv P ART 4 M ASTER TRAINING 287 13 ■ Surviving events 289 14 ■ Manipulating the DOM 329 15 ■ CSS selector engines 345 www.it-ebooks.info v contents preface xi acknowledgments xiii about this book xv about the authors xx P ART 1 P REPARING FOR TRAINING . 1 1 Enter the ninja 3 1.1 The JavaScript libraries we’ll be tapping 4 1.2 Understanding the JavaScript language 5 1.3 Cross-browser considerations 6 1.4 Current best practices 9 Current best practice: testing 9 ■ Current best practice: performance analysis 10 1.5 Summary 11 2 Arming with testing and debugging 13 2.1 Debugging code 14 Logging 14 ■ Breakpoints 16 www.it-ebooks.info CONTENTS vi 2.2 Test generation 17 2.3 Testing frameworks 19 QUnit 21 ■ YUI Test 22 ■ JsUnit 22 Newer unit-testing frameworks 22 2.4 The fundamentals of a test suite 22 The assertion 23 ■ Test groups 24 ■ Asynchronous testing 25 2.5 Summary 27 P ART 2 A PPRENTICE TRAINING 29 3 Functions are fundamental 31 3.1 What’s with the functional difference? 32 Why is JavaScript’s functional nature important? 33 Sorting with a comparator 37 3.2 Declarations 40 Scoping and functions 43 3.3 Invocations 46 From arguments to function parameters 47 ■ Invocation as a function 49 ■ Invocation as a method 50 ■ Invocation as a constructor 52 ■ Invocation with the apply() and call() methods 54 3.4 Summary 58 4 Wielding functions 61 4.1 Anonymous functions 62 4.2 Recursion 64 Recursion in named functions 64 ■ Recursion with methods 65 The pilfered reference problem 66 ■ Inline named functions 68 The callee property 70 4.3 Fun with function as objects 71 Storing functions 72 ■ Self-memoizing functions 73 Faking array methods 76 4.4 Variable-length argument lists 77 Using apply() to supply variable arguments 77 Function overloading 79 4.5 Checking for functions 86 4.6 Summary 88 www.it-ebooks.info CONTENTS vii 5 Closing in on closures 89 5.1 How closures work 90 5.2 Putting closures to work 94 Private variables 94 ■ Callbacks and timers 96 5.3 Binding function contexts 99 5.4 Partially applying functions 103 5.5 Overriding function behavior 106 Memoization 106 ■ Function wrapping 109 5.6 Immediate functions 111 Temporary scope and private variables 112 ■ Loops 115 Library wrapping 117 5.7 Summary 118 6 Object-orientation with prototypes 119 6.1 Instantiation and prototypes 120 Object instantiation 120 ■ Object typing via constructors 127 Inheritance and the prototype chain 128 HTML DOM prototypes 133 6.2 The gotchas! 135 Extending Object 135 ■ Extending Number 136 Subclassing native objects 137 ■ Instantiation issues 139 6.3 Writing class-like code 143 Checking for function serializability 146 ■ Initialization of subclasses 147 ■ Preserving super-methods 148 6.4 Summary 150 7 Wrangling regular expressions 151 7.1 Why regular expressions rock 152 7.2 A regular expression refresher 153 Regular expressions explained 153 ■ Terms and operators 154 7.3 Compiling regular expressions 158 7.4 Capturing matching segments 161 Performing simple captures 161 ■ Matching using global expressions 162 ■ Referencing captures 163 Non-capturing groups 165 7.5 Replacing using functions 166 www.it-ebooks.info CONTENTS viii 7.6 Solving common problems with regular expressions 168 Trimming a string 168 ■ Matching newlines 170 Unicode 171 ■ Escaped characters 172 7.7 Summary 172 8 Taming threads and timers 175 8.1 How timers and threading work 176 Setting and clearing timers 176 ■ Timer execution within the execution thread 177 ■ Differences between timeouts and intervals 179 8.2 Minimum timer delay and reliability 180 8.3 Dealing with computationally expensive processing 183 8.4 Central timer control 186 8.5 Asynchronous testing 189 8.6 Summary 190 P ART 3 N INJA TRAINING 191 9 Ninja alchemy: runtime code evaluation 193 9.1 Code evaluation mechanisms 194 Evaluation with the eval() method 194 ■ Evaluation via the Function constructor 197 ■ Evaluation with timers 197 Evaluation in the global scope 198 ■ Safe code evaluation 199 9.2 Function “decompilation” 201 9.3 Code evaluation in action 204 Converting JSON 204 ■ Importing namespaced code 205 JavaScript compression and obfuscation 206 ■ Dynamic code rewriting 208 ■ Aspect-oriented script tags 209 Metalanguages and DSLs 210 9.4 Summary 213 10 With statements 215 10.1 What’s with “with”? 216 Referencing properties within a with scope 216 ■ Assignments within a with scope 218 ■ Performance considerations 219 10.2 Real-world examples 221 10.3 Importing namespaced code 223 www.it-ebooks.info CONTENTS ix 10.4 Testing 223 10.5 Templating with “with” 224 10.6 Summary 227 11 Developing cross-browser strategies 229 11.1 Choosing which browsers to support 230 11.2 The five major development concerns 231 Browser bugs and differences 232 ■ Browser bug fixes 233 Living with external code and markup 234 Missing features 239 ■ Regressions 240 11.3 Implementation strategies 242 Safe cross-browser fixes 242 ■ Object detection 243 Feature simulation 245 ■ Untestable browser issues 247 11.4 Reducing assumptions 249 11.5 Summary 251 12 Cutting through attributes, properties, and CSS 253 12.1 DOM attributes and properties 255 Cross-browser naming 256 ■ Naming restrictions 257 Differences between XML and HTML 257 ■ Behavior of custom attributes 258 ■ Performance considerations 258 12.2 Cross-browser attribute issues 262 DOM id/name expansion 262 ■ URL normalization 264 The style attribute 265 ■ The type attribute 265 The tab index problem 266 ■ Node names 267 12.3 Styling attribute headaches 267 Where are my styles? 268 ■ Style property naming 270 The float style property 271 ■ Conversion of pixel values 271 Measuring heights and widths 272 ■ Seeing through opacity 276 ■ Riding the color wheel 279 12.4 Fetching computed styles 282 12.5 Summary 285 P ART 4 M ASTER TRAINING 287 13 Surviving events 289 13.1 Binding and unbinding event handlers 290 13.2 The Event object 294 www.it-ebooks.info [...]... Understanding the JavaScript language ■ ■ ■ 5 Advanced use of the JavaScript language Meticulous construction of cross-browser code The use of current best practices that tie everything together We’ll be carefully analyzing these three aspects in each of the libraries to gather a complete knowledge base we can use to create our own effective JavaScript code 1.2 Understanding the JavaScript language Many JavaScript. .. comprehensively For these reasons, they’ll serve as a good basis for further analysis, and understanding the fundamental construction of these code bases will give us insight into the process of world-class JavaScript library construction But these techniques aren’t only useful for constructing large libraries; they can be applied to all JavaScript coding, regardless of size The makeup of a JavaScript library... multiple considerations, the primary of which are ■ ■ ■ The expectations and needs of the target audience The market share of the browser The amount of effort necessary to support the browser The first point is a subjective one that only your project can determine Market share, on the other hand, can frequently be measured using available information And a rough estimate of the effort involved in supporting... 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... that depict the rich diversity of traditional costumes from around the world, brought back to life by prints such as this one www.it-ebooks.info about the authors John Resig is the Dean of Computer Science at Khan Academy and the creator of the jQuery JavaScript library jQuery is currently used in 58% of the top 10,000 websites (according to BuiltWith.com) and is used on tens of millions of other sites,... 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 understanding of JavaScript, the. .. chapter 6, where we learn how patterns of objects can be created through the prototype property of the function, and we’ll learn how objects are tied to functions for their definitions—one of the many reasons we discussed functions first Chapter 7 focuses on the regular expression, an often-overlooked feature of the language that can do the work of scores of lines of code when used correctly We’ll learn... 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 accessible from the publisher’s website as long as the book is in print About the cover illustration The figure on the. .. 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 Audience This is not your first JavaScript book If you’re a complete novice to JavaScript, ... 349 The pure-DOM implementation 351 Parsing the selector 353 Finding the elements 354 Filtering the set 355 Recursing and merging 356 Bottom-up selector engine 357 ■ ■ 15.4 Summary index 359 361 www.it-ebooks.info preface When I started writing Secrets of the JavaScript Ninja years ago, in early 2008, I saw a real need: there were no books providing in-depth coverage of the most important parts of the . started writing Secrets of the JavaScript Ninja years ago, in early 2008, I saw a real need: there were no books providing in-depth coverage of the most important parts of the JavaScript language. 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. 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

Ngày đăng: 05/05/2014, 12:32

Từ khóa liên quan

Mục lục

  • Front cover

  • brief contents

  • contents

  • preface

  • acknowledgments

    • John Resig

    • Bear Bibeault

    • about this book

      • Audience

      • Roadmap

      • Code conventions

      • Code downloads

      • Author online

      • About the cover illustration

      • about the authors

      • Part 1—Preparing for training

        • 1 Enter the ninja

          • 1.1 The JavaScript libraries we’ll be tapping

          • 1.2 Understanding the JavaScript language

          • 1.3 Cross-browser considerations

          • 1.4 Current best practices

            • 1.4.1 Current best practice: testing

            • 1.4.2 Current best practice: performance analysis

            • 1.5 Summary

            • 2 Arming with testing and debugging

              • 2.1 Debugging code

                • 2.1.1 Logging

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan