Object-Oriented JavaScript 3rd Edition (Ved Antani, Stoyan Stefanov) (z-library.sk, 1lib.sk, z-lib.sk)
JavaScriptAuthor:Ved Antani, Stoyan Stefanov
No description
Tags
Support Statistics
¥.00 ·
0times
Text Preview (First 20 pages)
Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
(This page has no text content)
Page
2
Object-Oriented JavaScript Third Edition Learn everything you need to know about object-oriented JavaScript with this comprehensive guide. Enter the world of cutting-edge development! Ved Antani Stoyan Stefanov BIRMINGHAM - MUMBAI
Page
3
Object-Oriented JavaScript Third Edition Copyright © 2017 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the authors, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: July 2008 Second edition: July 2013 Third edition: January 2017 Production reference: 1050117 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78588-056-8 www.packtpub.com
Page
4
Credits Authors Ved Antani Stoyan Stefanov Copy Editor Zainab Bootwala Reviewer Mohamed Sanaulla Project Coordinator Ritika Manoj Commissioning Editor Wilson Dsouza Proofreader Safis Editing Acquisition Editor Denim Pinto Indexer Rekha Nair Content Development Editor Arun Nadar Graphics Jason Monteiro Technical Editor Abhishek Sharma Production Coordinator Arvindkumar Gupta
Page
5
About the Authors Ved Antani has been building scalable server and mobile platforms using JavaScript, Go, and Java since 2005. He is an associate vice president at Myntra and has previously worked at Electronic Arts and Oracle. He is an avid reader and author on several subjects. He has studied computer science and currently lives in Bangalore, India. Ved is passionate about classical music and loves to spend time with his son. Writing this book required a significant investment of my time, and I would like to thank my parents and family for their support and encouragement during those long days and weekends when I was practically invisible. Stoyan Stefanov is a Facebook engineer, author, and speaker. He talks regularly about web development topics at conferences, and his blog, www.phpied.com. He also runs a number of other sites, including JSPatterns.com - a site dedicated to exploring JavaScript patterns. Previously at Yahoo!, Stoyan was the architect of YSlow 2.0 and creator of the image optimization tool, Smush.it. A "citizen of the world", Stoyan was born and raised in Bulgaria, but is also a Canadian citizen, currently residing in Los Angeles, California. In his offline moments, he enjoys playing the guitar, taking flying lessons, and spending time at the Santa Monica beaches with his family. I'd like to dedicate this book to my wife, Eva, and my daughters, Zlatina and Nathalie. Thank you for your patience, support, and encouragement.
Page
6
About the Reviewer Mohamed Sanaulla is a software developer with more than 7 years of experience in developing enterprise applications and Java-based back-end solutions for e-commerce applications. His interests include Enterprise software development, refactoring and redesigning applications, designing and implementing RESTful web services, troubleshooting Java applications for performance issues, and TDD. He has strong expertise in Java-based application development, ADF (JSF-based JavaEE web framework), SQL, PL/SQL, JUnit, designing RESTful services, Spring, Struts, Elasticsearch, and MongoDB. He is also a Sun Certified Java Programmer for the Java 6 platform. He is a moderator for JavaRanch.com. He likes to share findings on his blog (h t t p ://s a n a u l l a . i n f o ).
Page
7
www.PacktPub.com For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. h t t p s ://w w w . p a c k t p u b . c o m /m a p t Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career. Why subscribe? Fully searchable across every book published by Packt Copy and paste, print, and bookmark content On demand and accessible via a web browser
Page
8
Customer Feedback Thank you for purchasing this Packt book. We take our commitment to improving our content and products to meet your needs seriously--that's why your feedback is so valuable. Whatever your feelings about your purchase, please consider leaving a review on this book's Amazon page. Not only will this help us, more importantly it will also help others in the community to make an informed decision about the resources that they invest in to learn. You can also review for us on a regular basis by joining our reviewers' club. If you're interested in joining, or would like to learn more about the benefits we offer, please contact us: customerreviews@packtpub.com.
Page
9
Table of Contents Preface 1 Chapter 1: Object-Oriented JavaScript 6 A bit of history 7 Browser wars and renaissance 8 The present 9 The future 10 ECMAScript 5 11 Strict mode in ES6 12 ECMAScript 6 12 Browser support for ES6 13 Babel 13 Object-oriented programming 15 Objects 16 Classes 16 Encapsulation 17 Aggregation 18 Inheritance 18 Polymorphism 19 OOP summary 19 Setting up your training environment 20 WebKit's web inspector 21 JavaScriptCore on a Mac 22 More consoles 24 Summary 26 Chapter 2: Primitive Data Types, Arrays, Loops, and Conditions 27 Variables 27 Variables are case sensitive 29 Operators 30 Primitive data types 33 Finding out the value type – the typeof operator 34 Numbers 35 Octal and hexadecimal numbers 35 Binary Literals 36 Exponent literals 37
Page
10
[ ii ] Infinity 38 NaN 39 Number.isNaN 40 Number.isInteger 40 Strings 41 String conversions 42 Special strings 43 String template literals 44 Booleans 46 Logical operators 46 Operator precedence 48 Lazy evaluation 49 Comparison 50 Undefined and null 52 Symbols 53 Primitive data types recap 54 Arrays 55 Adding/updating array elements 56 Deleting elements 57 Arrays of arrays 57 Conditions and loops 59 Code blocks 59 The if condition 60 The else clause 60 Checking if a variable exists 61 Alternative if syntax 63 Switch 64 Don't forget to break 65 Loops 65 While loops 66 Do-while loops 67 For loops 67 For…in loops 70 Comments 71 Exercises 71 Summary 72 Chapter 3: Functions 73 What is a function? 74 Calling a function 74 Parameters 75 Default parameters 77 Rest parameters 78 Spread operators 79
Page
11
[ iii ] Predefined functions 80 parseInt() 80 parseFloat() 82 isNaN() 83 isFinite() 83 Encode/decode URIs 84 eval() 84 A bonus – the alert() function 85 Scope of variables 85 Variable hoisting 87 Block scope 88 Functions are data 90 Anonymous functions 92 Callback functions 92 Callback examples 94 Immediate functions 96 Inner (private) functions 97 Functions that return functions 98 Function, rewrite thyself! 99 Closures 101 Scope chain 101 Breaking the chain with a closure 102 Closure #1 105 Closure #2 106 A definition and closure #3 106 Closures in a loop 107 Getter and setter 109 Iterator 110 IIFE versus blocks 111 Arrow functions 112 Exercises 113 Summary 114 Chapter 4: Objects 116 From arrays to objects 116 Elements, properties, methods, and members 118 Hashes and associative arrays 119 Accessing an object's properties 119 Calling an object's methods 121 Altering properties/methods 122 Using the this value 123 Constructor functions 124
Page
12
[ iv ] The global object 125 The constructor property 126 The instanceof operator 127 Functions that return objects 128 Passing objects 129 Comparing objects 130 Objects in the WebKit console 130 Logging using the console.log method 132 ES6 object literals 133 Object properties and attributes 135 ES6 object methods 135 Copy properties using Object.assign 136 Compare values with Object.is 137 Destructuring 137 Built-in objects 140 Object 141 Array 142 A few array methods 144 ES6 array methods 146 Array.from 146 Creating arrays using Array.of 148 Array.prototype methods 148 Function 150 Properties of function objects 151 Using the prototype property 152 Methods of function objects 153 Call and apply 153 The arguments object revisited 155 Lexical this in arrow functions 155 Inferring object types 157 Boolean 158 Number 159 String 161 A few methods of string objects 162 Math 165 Date 168 Methods to work with date objects 170 Calculating birthdays 172 RegExp 172 Properties of RegExp objects 173 Methods of RegExp objects 174 String methods that accept regular expressions as arguments 175
Page
13
[ v ] search() and match() 175 replace() 176 Replace callbacks 177 split() 178 Passing a string when a RegExp is expected 179 Error objects 179 Exercises 183 Summary 185 Chapter 5: ES6 Iterators and Generators 187 For…of loop 187 Iterators and iterables 188 Iterators 188 Iterables 189 Generators 190 Iterating over generators 194 Collections 195 Map 195 Iterating over maps 196 Converting maps to arrays 198 Set 198 WeakMap and WeakSet 199 Summary 200 Chapter 6: Prototype 201 The prototype property 202 Adding methods and properties using the prototype 202 Using the prototype's methods and properties 204 Own properties versus prototype properties 205 Overwriting a prototype's property with an own property 206 Enumerating properties 207 Using isPrototypeOf() method 210 The secret __proto__ link 211 Augmenting built-in objects 213 Augmenting built-in objects – discussion 214 Prototype gotchas 215 Exercises 217 Summary 218 Chapter 7: Inheritance 219 Prototype chaining 220 Prototype chaining example 221
Page
14
[ vi ] Moving shared properties to the prototype 223 Inheriting the prototype only 226 A temporary constructor – new F() 227 Uber – access to the parent from a child object 229 Isolating the inheritance part into a function 231 Copying properties 232 Heads-up when copying by reference 235 Objects inherit from objects 238 Deep copy 240 Using object() method 241 Using a mix of prototypal inheritance and copying properties 242 Multiple inheritance 244 Mixins 246 Parasitic inheritance 246 Borrowing a constructor 247 Borrowing a constructor and copying its prototype 250 Case study – drawing shapes 251 Analysis 251 Implementation 252 Testing 256 Exercises 257 Summary 258 Chapter 8: Classes and Modules 262 Defining classes 264 Constructor 266 Prototype methods 266 Static methods 267 Static properties 268 Generator methods 268 Subclassing 268 Mixins 270 Modules 272 Export lists 274 Summary 275 Chapter 9: Promises and Proxies 276 Asynchronous programming model 278 JavaScript call stack 281 Message queue 281
Page
15
[ vii ] Event loop 282 Timers 282 Run to completion 282 Events 283 Callbacks 283 Promises 285 Creating promises 287 Promise.all() 289 Metaprogramming and proxies 289 Proxy 290 Function traps 292 Summary 293 Chapter 10: The Browser Environment 294 Including JavaScript in an HTML page 294 BOM and DOM – an overview 295 BOM 296 The window object revisited 296 Using window.navigator property 297 Your console is a cheat sheet 298 Using window.location property 299 Using window.history property 300 using window.frames property 301 Using window.screen property 303 window.open()/close() method 303 window.moveTo() and window.resizeTo() methods 304 window.alert(), window.prompt(), and window.confirm() methods 305 Using window.setTimeout() and window.setInterval() methods 307 window.document property 309 DOM 309 Core DOM and HTML DOM 312 Accessing DOM nodes 313 The document node 314 documentElement 316 Child nodes 317 Attributes 318 Accessing the content inside a tag 319 DOM access shortcuts 320 Siblings, body, first, and last child 322 Walk the DOM 323 Modifying DOM nodes 324 Modifying styles 324
Page
16
[ viii ] Fun with forms 325 Creating new nodes 327 DOM-only method 328 Using cloneNode() method 329 Using insertBefore() method 330 Removing nodes 330 HTML – only DOM objects 332 Primitive ways to access the document 333 Using document.write() method 334 Cookies, title, referrer, and domain 335 Events 336 Inline HTML attributes 337 Element Properties 337 DOM event listeners 338 Capturing and bubbling 338 Stop propagation 340 Prevent default behavior 342 Cross-browser event listeners 343 Types of events 344 XMLHttpRequest 345 Sending the request 346 Processing the response 347 Creating XMLHttpRequest objects in IE prior to Version 7 348 A is for Asynchronous 349 X is for XML 350 An example 350 Exercises 353 Summary 355 Chapter 11: Coding and Design Patterns 357 Coding patterns 358 Separating behavior 358 Content 358 Presentation 359 Behavior 359 Example of separating behavior 360 Asynchronous JavaScript loading 361 Namespaces 361 An Object as a namespace 362 Namespaced constructors 362 A namespace() method 363 Init-time branching 364
Page
17
[ ix ] Lazy definition 365 Configuration object 366 Private properties and methods 369 Privileged methods 370 Private functions as public methods 370 Immediate functions 371 Modules 372 Chaining 373 JSON 374 Higher order functions 375 Design patterns 377 Singleton pattern 378 Singleton 2 pattern 378 Global variable 378 Property of the constructor 379 In a private property 380 Factory pattern 380 Decorator pattern 382 Decorating a christmas tree 383 Observer pattern 384 Summary 388 Chapter 12: Testing and Debugging 389 Unit testing 390 Test Driven Development 391 Behavior Driven Development 391 Mocha, Chai and Sinon 397 JavaScript debugging 398 Syntax errors 398 Using strict 399 Runtime exceptions 399 Console.log and asserts 400 Chrome Developer Tools 401 Summary 407 Chapter 13: Reactive Programming and React 408 Reactive programming 408 Why should you consider reactive programming? 411 React 412 Virtual DOM 412 Installing and running react 413 Components and props 417
Page
18
[ x ] State 418 Life cycle events 421 Summary 422 Appendix A: Reserved Words 423 Keywords 423 ES6 reserved words 424 Future reserved words 425 Previously reserved words 425 Appendix B: Built-in Functions 427 Appendix C: Built-in Objects 430 Object 430 Members of the Object constructor 431 The Object.prototype members 431 ECMAScript 5 additions to objects 433 ES6 addition to objects 438 Property shorthand 438 Computed property names 438 Object.assign 439 Array 439 The Array.prototype members 440 ECMAScript 5 additions to Array 443 ES6 addition to arrays 447 Function 449 The Function.prototype members 449 ECMAScript 5 additions to a Function 450 ECMAScript 6 additions to a Function 451 Boolean 451 Number 452 Members of the Number constructor 453 The Number.prototype members 453 String 454 Members of the String constructor 455 The String.prototype members 456 ECMAScript 5 additions to String 458 ECMAScript 6 additions to String 459 Date 459 Members of the Date constructor 460 The Date.prototype members 461
Page
19
[ xi ] ECMAScript 5 additions to Date 464 Math 464 Members of the Math object 465 RegExp 466 The RegExp.prototype members 467 Error objects 468 The Error.prototype members 469 JSON 469 Members of the JSON object 470 Appendix D: Regular Expressions 472 Appendix E: Answers to Exercise Questions 477 Chapter 2, Primitive Data Types, Arrays, Loops, and Conditions 477 Exercises 477 Chapter 3, Functions 481 Exercises 481 Chapter 4, Objects 485 Exercises 485 Chapter 5, Prototype 494 Exercises 494 Chapter 6, Inheritance 495 Exercises 495 Chapter 7, The Browser Environment 503 Exercises 503 Index 511
Page
20
Preface JavaScript has emerged as one of the most robust and versatile programming language around. Modern JavaScript embraces a vast array of time-tested and cutting edge features. Several of these features are slowly giving shape to the next generation of web and server platforms. ES6 introduces very important language constructs, such as promises, classes, arrow functions, and several, much anticipated features. This book takes a detailed look at the language constructs and their practical uses. This book doesn't assume any prior knowledge of JavaScript and works from the ground up to give you a thorough understanding of the language. People who know the language will still find it useful and informative. For people who already know JavaScript and are familiar with ES5 syntax, this book will be a very useful primer for ES6 features. What this book covers Chapter 1, Object-Oriented JavaScript, talks briefly about the history, present, and future of JavaScript, and then moves on to explore the basics of object-oriented programming (OOP) in general. You will then learn how to set up your training environment (Firebug) in order to dive into the language on your own, using the book examples as a base. Chapter 2, Primitive Data Types, Arrays, Loops, and Conditions, discusses the language basics- -variables, data types, primitive data types, arrays, loops, and conditionals. Chapter 3, Functions, covers functions that JavaScript uses, and here you will learn to master them all. You will also learn about the scope of variables and JavaScript's built-in functions. An interesting, but often misunderstood, feature of the language--closures--is demystified at the end of the chapter. Chapter 4, Objects, talks about objects, how to work with properties and methods, and the various ways to create your objects. This chapter also talks about built-in objects such as Array, Function, Boolean, Number, and String. Chapter 5, ES6 Iterators and Generators, introduces the most anticipated features of ES6, Iterators and Generators. With this knowledge, you will proceed to take a detailed look at the enhanced collections constructs.
Comments 0
Loading comments...
Reply to Comment
Edit Comment