483 Professional JavaScript for Web Developers, 3rd Edition

Gratis

0
0
964
3 months ago
Preview
Full text

CHAPTER 25 Emerging APIs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835 APPENDIX A ECMAScript Harmony . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857 APPENDIX B Strict Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877 APPENDIX C JavaScript Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885 APPENDIX D JavaScript Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891 INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

  897 PROFESSIONAL® JavaScript for Web Developers John Wiley & Sons, Inc. Zakas Professional JavaScript® for Web Developers, Third EditionPublished by John Wiley & Sons, Inc.

ISBN: 978-1-118-02669-4

  Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties withrespect to the accuracy or completeness of the contents of this work and specifi cally disclaim all warranties, including without limitation warranties of fi tness for a particular purpose. The fact that an organization or Web site isreferred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or Web site may provide or recommendations it may make.

ABOUT THE AUTHOR NICHOLAS C. ZAKAS

ABOUT THE TECHNICAL EDITOR JOHN PELOQUIN

  in mathematics from the University of California atBerkeley and is currently a lead developer for a health care startup where he makes use of the latest in front-end technologies. They were the only people willing to take a risk on an unknown author for the fi rst edition of Professional JavaScript for Web Developers, and for that I will be forever grateful.

CHAPTER 1: WHAT IS JAVASCRIPT?

CHAPTER 2: JAVASCRIPT IN HTML

20 Inline Code versus External Files 31 31 The typeof Operator 28 Variables 29 Data Types 27 Statements 27Keywords and Reserved Words 26 Comments 26 Strict Mode 25 Syntax 25Case-sensitivity 25 Identifi ers 22 Summary 22 20 The <noscript> Element 20 Document Modes 18 Deprecated Syntax INTRODUCTION xxxiii 17 Changes in XHTML 16 Asynchronous Scripts 16 Deferred Scripts 13 Tag Placement 13 The <script> Element 10 Summary 11 9 JavaScript Versions 6 The Browser Object Model (BOM) 3 ECMAScript 3The Document Object Model (DOM) 2 JavaScript Implementations 1 A Short History

CHAPTER 3: LANGUAGE BASICS

CONTENTSThe Undefi ned Type 32 The Null Type 33 The Boolean Type 34 The Number Type 35 The String Type 41 The Object Type 44 Operators 45 Unary Operators 46 Bitwise Operators 49 Boolean Operators 56 Multiplicative Operators 59 Additive Operators 61 Relational Operators 63 Equality Operators 65 Conditional Operator 67 Assignment Operators 67 Comma Operator 68 Statements 69 The if Statement 69 The do-while Statement 70 The while Statement 70 The for Statement 71 The for-in Statement 72 Labeled Statements 73 The break and continue Statements 73 The with Statement 75 The switch Statement 76 Functions 78 Understanding Arguments 80 No Overloading 83 Summary 83

CHAPTER 4: VARIABLES, SCOPE, AND MEMORY

85 Primitive and Reference Values 85 Dynamic Properties 86 Copying Values 86 Argument Passing 88 Determining Type 89 Execution Context and Scope 90 Scope Chain Augmentation 92 No Block-Level Scopes 93xvi

CHAPTER 5: REFERENCE TYPES 103 The Object Type

136No Overloading (Revisited) Summary 170D o w n lo a d f ro m W o w ! e B o o k < w w w .w o w e b o o k .c o m > 162 The Math Object166 161The Global Object 151Singleton Built-in Objects The Boolean Type148 The Number Type149 The String Type Primitive Wrapper Types146 139 Function Internals141 Function Properties and Methods 143 138 Function Declarations versus Function Expressions 138Functions as Values xvii CONTENTS Garbage Collection 96 Mark-and-Sweep 96Reference Counting 132 RegExp Constructor Properties 134Pattern Limitations RegExp Instance Properties131 RegExp Instance Methods The RegExp Type128 Inherited Methods124 Date-Formatting Methods125 Date/Time Component Methods 126 The Date Type122 Detecting Arrays110 Conversion Methods110 Stack Methods112 Queue Methods113 Reordering Methods114 Manipulation Methods116 Location Methods118 Iterative Methods119 Reduction Methods121 104 The Array Type106 99 Summary 100 97 Performance 98 Managing Memory 136The Function Type CONTENTS CHAPTER 6: OBJECT-ORIENTED PROGRAMMING 173 Understanding Objects173 Types of Properties174 Defi ning Multiple Properties 178 Reading Property Attributes179 Object Creation180 The Factory Pattern180 The Constructor Pattern 181 The Prototype Pattern184 Combination Constructor/Prototype Pattern 197 Dynamic Prototype Pattern198 Parasitic Constructor Pattern 199 Durable Constructor Pattern200 Inheritance 201Prototype Chaining 202 Constructor Stealing207 Combination Inheritance 209 Prototypal Inheritance210 Parasitic Inheritance 211 Parasitic Combination Inheritance 212Summary 215 CHAPTER 7: FUNCTION EXPRESSIONS 217 Recursion 220 Closures 221 Closures and Variables224 The this Object 225 Memory Leaks227 Mimicking Block Scope228 Private Variables 231Static Private Variables 232 The Module Pattern234 The Module-Augmentation Pattern 236 Summary 237 CHAPTER 8: THE BROWSER OBJECT MODEL 239 The window Object239 The Global Scope240 Window Relationships and Frames 241 Window Position244xviii CONTENTSWindow Size 245 Navigating and Opening Windows 247Intervals and Timeouts 251 System Dialogs253 The location Object255 Query String Arguments256 Manipulating the Location 257The Navigator Object 259Detecting Plug-ins 262 Registering Handlers264 The screen Object265 The history Object 267 Summary 268 CHAPTER 9: CLIENT DETECTION 271 Capability Detection271 Safer Capability Detection273 Capability Detection Is Not Browser Detection 274 Quirks Detection275 User-Agent Detection276 History 277 Working with User-Agent Detection 286The Complete Script 303 Usage 306Summary 306 CHAPTER 10: THE DOCUMENT OBJECT MODEL 309 Hierarchy of Nodes310 The Node Type310 The Document Type316 The Element Type 326 The Text Type337 The Comment Type 341 The CDATASection Type342 The DocumentType Type343 The DocumentFragment Type 344 The Attr Type345 Working with the DOM346 Dynamic Scripts346 Dynamic Styles348xix CONTENTSManipulating Tables 350 Using NodeLists353 Summary 354 CHAPTER 11: DOM EXTENSIONS 357 Selectors API357 The querySelector() Method358 The querySelectorAll() Method 358 The matchesSelector() Method 359Element Traversal 360 HTML5 361Class-Related Additions 361 Focus Management364 Changes to HTMLDocument364 Character Set Properties 366 Custom Data Attributes366 Markup Insertion 367 The scrollIntoView() Method372 Proprietary Extensions372 Document Mode373 The children Property 374 The contains() Method374 Markup Insertion 376 Scrolling 379Summary 379 CHAPTER 12: DOM LEVELS 2 AND 3 381 DOM Changes382 XML Namespaces382 Other Changes 386Styles 390 Accessing Element Styles391 Working with Style Sheets 396 Element Dimensions401 Traversals 408NodeIterator 410 TreeWalker 413 Ranges 415Ranges in the DOM 415 Ranges in Internet Explorer 8 and Earlier 424Summary 428 xx CONTENTS

CHAPTER 13: EVENTS

431 Event Flow432 Event Bubbling432 Event Capturing433 DOM Event Flow433 Event Handlers434 HTML Event Handlers434 DOM Level 0 Event Handlers 437 DOM Level 2 Event Handlers438 Internet Explorer Event Handlers 439 Cross-Browser Event Handlers 441The Event Object 442The DOM Event Object 442 The Internet Explorer Event Object 447Cross-Browser Event Object 449Event Types 451UI Events 452 Focus Events458 Mouse and Wheel Events459 Keyboard and Text Events 471 Composition Events478 Mutation Events 479 HTML5 Events482 Device Events490 Touch and Gesture Events 494Memory and Performance 498Event Delegation 498 Removing Event Handlers500 Simulating Events502 DOM Event Simulation502 Internet Explorer Event Simulation 508 Summary 509

CHAPTER 14: SCRIPTING FORMS 511 Form Basics

511Submitting Forms 512 Resetting Forms513 Form Fields514 Scripting Text Boxes520 Text Selection521xxi CONTENTSInput Filtering 524 Automatic Tab Forward528 HTML5 Constraint Validation API 530 Scripting Select Boxes534 Options Selection536 Adding Options 537 Removing Options538 Moving and Reordering Options 539 Form Serialization540 Rich Text Editing542 Using contenteditable543 Interacting with Rich Text543 Rich Text Selections547 Rich Text in Forms 549Summary 549 CHAPTER 15: GRAPHICS WITH CANVAS 551 Basic Usage551 The 2D Context 553Fills and Strokes 553 Drawing Rectangles553 Drawing Paths 556 Drawing Text557 Transformations 559 Drawing Images563 Shadows 564 Gradients 565 Patterns 567Working with Image Data 567 Compositing 569WebGL 571 Typed Arrays571 The WebGL Context 576 Support 588Summary 588

CHAPTER 16: HTML5 SCRIPTING 591 Cross-Document Messaging 591 Native Drag and Drop

593Drag-and-Drop Events 593xxii CONTENTSCustom Drop Targets 594 The dataTransfer Object595 DropEff ect and eff ectAllowed 596 Draggability 597 Additional Members598 Media Elements598 Properties 599 Events 601Custom Media Players 602 Codec Support Detection603 The Audio Type604 History State Management605 Summary 606

CHAPTER 17: ERROR HANDLING AND DEBUGGING 607 Browser Error Reporting

607Internet Explorer 608 Firefox 609Safari 610 Opera 612Chrome 613 Error Handling614 The try-catch Statement615 Throwing Errors619 The error Event 622 Error-handling Strategies623 Identify Where Errors Might Occur 623 Distinguishing between Fatal and Nonfatal Errors 628 Log Errors to the Server629 Debugging Techniques630 Logging Messages to a Console 631 Logging Messages to the Page 633Throwing Errors 634Common Internet Explorer Errors 635 Operation Aborted635 Invalid Character 637 Member Not Found637 Unknown Runtime Error 638 Syntax Error638 The System Cannot Locate the Resource Specifi ed 639 Summary 639 xxiii CONTENTS CHAPTER 18: XML IN JAVASCRIPT 641 XML DOM Support in Browsers 641 DOM Level 2 Core641 The DOMParser Type 642 The XMLSerializer Type644 XML in Internet Explorer 8 and Earlier 644 Cross-Browser XML Processing 649 XPath Support in Browsers651 DOM Level 3 XPath651 XPath in Internet Explorer656 Cross-Browser XPath 657 XSLT Support in Browsers660 XSLT in Internet Explorer660 The XSLTProcessor Type665 Cross-Browser XSLT 667Summary 668 CHAPTER 19: ECMASCRIPT FOR XML 671 E4X Types671 The XML Type672 The XMLList Type673 The Namespace Type 674 The QName Type675 General Usage676 Accessing Attributes678 Other Node Types679 Querying 681 XML Construction and Manipulation 682 Parsing and Serialization Options 685Namespaces 686 Other Changes688 Enabling Full E4X689 Summary 689

CHAPTER 20: JSON

691 Syntax 691Simple Values 692 Objects 692Arrays 693 Parsing and Serialization694 xxiv CONTENTSThe JSON Object 695 Serialization Options696 Parsing Options699 Summary 700 CHAPTER 21: AJAX AND COMET 701 The XMLHttpRequest Object 702 XHR Usage703 HTTP Headers706 GET Requests 707 POST Requests708 XMLHttpRequest Level 2710 The FormData Type710 Timeouts 711 The overrideMimeType() Method 711Progress Events 712The load Event 712 The progress Event713 Cross-Origin Resource Sharing 714CORS in Internet Explorer 714 CORS in Other Browsers716 Prefl ighted Requests 717 Credentialed Requests718 Cross-Browser CORS718 Alternate Cross-Domain Techniques 719Image Pings 719 Comet 721Server-Sent Events 723 Web Sockets725 SSE versus Web Sockets 727Security 728 Summary 729 CHAPTER 22: ADVANCED TECHNIQUES 731 Advanced Functions731 Safe Type Detection731 Scope-Safe Constructors 733 Lazy Loading Functions736 Function Binding738 Function Currying 741xxv CONTENTS Tamper-Proof Objects743 Nonextensible Objects744 Sealed Objects744 Frozen Objects745 Advanced Timers746 Repeating Timers748 Yielding Processes 750 Function Throttling752 Custom Events755 Drag and Drop758 Fixing Drag Functionality760 Adding Custom Events762 Summary 764 CHAPTER 23: OFFLINE APPLICATIONS AND CLIENT-SIDE STORAGE 765 Offl ine Detection765 Application Cache766 Data Storage768 Cookies 768 Internet Explorer User Data778 Web Storage 780 IndexedDB 786Summary 799 CHAPTER 24: BEST PRACTICES 801 Maintainability 801 What Is Maintainable Code?802 Code Conventions802 Loose Coupling805 Programming Practices809 Performance 814Be Scope-Aware 814 Choose the Right Approach816 Minimize Statement Count 821 Optimize DOM Interactions824 Deployment 827Build Process 827 Validation 829Compression 830 Summary 833 xxvi CONTENTS

CHAPTER 25: EMERGING APIS 835 RequestAnimationFrame() 835 Early Animation Loops

836 Problems with Intervals836 mozRequestAnimationFrame 837webkitRequestAnimationFrame and msRequestAnimationFrame 838 Page Visibility API839 Geolocation API 841 File API843 The FileReader Type844 Partial Reads 846 Object URLs847 Drag-and-Drop File Reading 848 File Upload with XHR849 Web Timing851 Web Workers 852Using a Worker 852 Worker Global Scope853 Including Other Scripts855 The Future of Web Workers855 Summary 856 APPENDIX A: ECMASCRIPT HARMONY 857 General Changes857 Constants 858 Block-Level and Other Scopes 858Functions 859 Rest and Spread Arguments859 Default Argument Values860 Generators 861 Arrays and Other Structures861 Iterators 862 Array Comprehensions863 Destructuring Assignments864 New Object Types865 Proxy Objects865 Proxy Functions868 Map and Set868 WeakMap 869 StructType 869xxvii CONTENTSArrayType 870 Classes 871Private Members 872 Getters/Setters 872Inheritance 873 Modules 874External Modules 875

APPENDIX B: STRICT MODE

  I had to check it out, and as I read about it, I was fl ooredwhen I realized that the toy language I had so readily dismissed was now the technology that was on the lips of every professional web developer. Here was one of top JavaScript developers in the world working on one of the most important web properties in the world (Yahoo!), and he was one of the nicest people I had ever met.

INTRODUCTION SOME CLAIM THAT JAVASCRIPT

WHO THIS BOOK IS FOR

  is now the most popular programming language in the world, running any number of complex web applications that the world relies on to do business, make purchases,manage processes, and more. This book is aimed at three groups of readers: ➤ Experienced developers familiar with object-oriented programming who are looking to learn JavaScript as it relates to traditional OO languages such as Java and C++.➤ Web application developers attempting to enhance the usability of their web sites and web applications.➤ Novice JavaScript developers aiming to better understand the language.

INTRODUCTION WHAT THIS BOOK COVERS

  A detailed discussion of the components that make up a JavaScript implementation follows,with specifi c focus on standards such as ECMAScript and the Document Object Model (DOM). The last part of the book is focused on advanced topics including performance/memory optimization, best practices, and a look at where JavaScript is going in the future.

HOW THIS BOOK IS STRUCTURED

  Introduces the various ways of embedding JavaScript into a page including a discussion surrounding the JavaScript content-type and its relationship to the <script> element. A brief introduction to XML and its relationship to the DOM gives way to an in-depth exploration of the entire DOM and howit allows developers to manipulate a page.

WHAT YOU NEED TO USE THIS BOOK

To run the samples in the book, you need the following: ➤ Windows XP, Windows 7, or Mac OS X ➤ Internet Explorer 6 or higher, Firefox 2 or higher, Opera 9 or higher, Chrome, or Safari 2 or higher The complete source code for the samples is available for download from the web site at www.wrox.com . xxxvi

INTRODUCTION CONVENTIONS

  SOURCE CODE As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code fi les that accompany the book. When at the site, simply locate the book’s title(use the Search box or one of the title lists) and click the Download Code link on the book’s detail page to obtain all the source code for the book.

P2P.WROX.COM

  The forums are a Web-based system for you to post messages relating to Wrox books and related technologies and interact withother readers and technology users. The forums offer a subscription feature to e-mail you topics of interest of your choosing when new posts are made to the forums.

3. Complete the required information to join, as well as any optional information you wish to provide, and click Submit

  If you would like to have new messages from a particular forume-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing. For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to questions about how the forum software works, as well as many common questions specifi c to P2Pand Wrox books.

1 D

  Brendan Eich, who worked for Netscape at the time, began developing a scripting language calledMocha, and later LiveScript, for the release of Netscape Navigator 2 in 1995, with the intention of using it both in the browser and on the server (where it was to be called LiveWire). This major step for Microsoft into therealm of web browsers in August 1996 is now a date that lives in infamy for Netscape, but it also represented a major step forward in the development of JavaScript as a language.

JAVASCRIPT IMPLEMENTATIONS

  On a very basic level, it describes the following parts of the language: ➤ Syntax Types ➤ ➤ Statements Keywords ➤ ➤ Reserved words Operators ➤ ➤ Objects ECMAScript is simply a description of a language implementing all of the facets described in the specifi cation. ❘ same as Netscape’s JavaScript 1.1 but with all references to browser-specifi c code removed and a few minor changes: ECMA-262 required support for the Unicode standard (to support multiplelanguages) and that objects be platform-independent (Netscape JavaScript 1.1 actually had different implementations of objects, such as the Date object, depending on the platform).

CHAPTER 1 WHAT IS JAVASCRIPT? BROWSER ECMASCRIPT COMPLIANCE Netscape Navigator 2 — Netscape Navigator 3 — Netscape Navigator 4–4.05 — Netscape Navigator 4.06–4.79 Edition 1 Netscape 6+ (Mozilla 0.6.0+) Edition 3 Internet Explorer 3 — Internet Explorer 4 — Internet Explorer 5 Edition 1 Internet Explorer 5.5–7 Edition 3 Internet Explorer 8 Edition 5* Internet Explorer 9+ Edition 5 Opera 6–7.1 Edition 2 Opera 7.2+ Edition 3 Safari 1–2.0.x Edition 3* Safari 3.x Edition 3 Safari 4.x–5.x Edition 5* Chrome 1+ Edition 3 Firefox 1–2 Edition 3 Firefox 3.0.x Edition 3 Firefox 3.5–3.6 Edition 5* Firefox 4+ Edition 5

  It consisted of two modules: the DOM Core, which provided a way to map the structure of an XML-based document to allowfor easy access to and manipulation of any part of a document, and the DOM HTML, which extended the DOM Core by adding HTML-specifi c objects and methods. Whereas the goal of DOM Level 1 was to map out the structure of a document, the aims of DOMLevel 2 were much broader.

BROWSER DOM COMPLIANCE

  This changed with the introduction of HTML5, which sought to codifymuch of the BOM as part of a formal specifi cation. Primarily, the BOM deals with the browser window and frames, but generally any browser-specifi c extension to JavaScript is considered to be a part of the BOM.

CHAPTER 1 WHAT IS JAVASCRIPT? The location object, which gives detailed information about the page loaded in the

  browserThe screen object, which gives detailed information about the user’s screen resolutionSupport for cookiesCustom objects such as XMLHttpRequest and Internet Explorer’s ActiveXObject Because no standards existed for the BOM for a long time, each browser has its own implementation. With HTML5 now available, the implementation details of the BOM are expected to grow in a much more compatible way.

JAVASCRIPT VERSIONS

  Mozilla, as a descendant from the original Netscape, is the only browser vendor that has continued the original JavaScript version-numbering sequence. When the Netscape source code was spun offinto an open-source project (named the Mozilla Project), the last browser version of JavaScript was 1.3.

BROWSER JAVASCRIPT VERSION

  Much like an <img> element, the <script> element’s src attribute may be set to a full URL that exists outside the domain on which the HTML page exists, as in this example: <script type=”text/javascript” src=”http://www.somewhere.com/afile.js”></script> Code from an external domain will be loaded and interpreted as if it were part of the page that is loading it. The fi nal solution was to enclose the script code in anHTML comment, like this: <script><!--function sayHi(){ alert(“Hi!”);}//--></script> Using this format, browsers like Mosaic would safely ignore the content inside of the <script> tag, and browsers that supported JavaScript had to look for this pattern to recognize that there wasindeed JavaScript content to be parsed.

INLINE CODE VERSUS EXTERNAL FILES

  Keeping in mind that there areno hard and fast rules regarding this practice, the arguments for using external fi les are as follows: Maintainability — JavaScript code that is sprinkled throughout various HTML pages turns➤ code maintenance into a problem. It is much easier to have a directory for all JavaScript fi les so that developers can edit JavaScript code independent of the markup in which it’s used.

DOCUMENT MODES

  The following are key points: ➤ To include external JavaScript fi les, the src attribute must be set to the URL of the fi le to include, which may be a fi le on the same server as the containing page or one that exists on a completely different domain. Deferred scripts always execute in the order in which they are specifi ed.➤ You can indicate that a script need not wait for other scripts and also not block the document rendering by using the async attribute.

3 Language Basics WHAT’S IN THIS CHAPTER?

  o .c By convention, ECMAScript identifi ers use camel case, meaning that the fi rst letter is lowercase and b e o o k each additional word is offset by a capital letter, like this:o w firstSecond .w myCar w w w < Although this is not strictly enforced, it is considered a best practice to adhere to the built-in k o doSomethingImportantW Keywords, reserved words, , , and cannot be used as identifi ers. Statements Statements in ECMAScript are terminated by a semicolon, though omitting the semicolon makes the parser determine where the end of a statement occurs, as in the following examples: var sum = a + b //valid even without a semicolon - not recommended var diff = a - b; //valid - preferred Even though a semicolon is not required at the end of statements, it is recommended to always include one.

KEYWORDS AND RESERVED WORDS

  (Without initialization, it holds the special value undefined , which is discussed in the next section.)ECMAScript implements variable initialization, so it’s possible to defi ne the variable and set its value at the same time, as in this example: var message = “hi”; Here, message is defi ned to hold a string value of “hi” . It is stillpossible to not only change the value stored in the variable but also change the type of value, such as this: var message = “hi”;message = 100; //legal, but not recommended 30 CHAPTER 3 LANGUAGE BASICS ❘ In this example, the variable message is fi rst defi ned as having the string value “hi” and then overwritten with the numeric value 100.

DATA TYPES

  Generally speaking, you should never explicitly set a variable to be .undefi ned The literal value is provided mainly for comparison and wasn’t addedundefi neduntil ECMA-262, third edition to help formalize the difference between an empty object pointer ( ) and an uninitialized variable.null Note that a variable containing the value of undefined is different from a variable that hasn’t been defi ned at all. Logically, a null value is an empty object pointer, which is why typeof returns “object” when it’s passed a null value in the following example: var car = null;alert(typeof car); //”object” NullExample01.htm When defi ning a variable that is meant to later hold an object, it is advisable to initialize the variable to null as opposed to anything else.

DATA TYPEVALUES CONVERTED TO TRUE

VALUES CONVERTED TO FALSE

  If a number out of this range is detected in the literal, then the leading zero is ignored and the number is treated as a decimal, as in the following examples: var octalNum1 = 070; //octal for 56 var octalNum2 = 079; //invalid octal - interpreted as 79var octalNum3 = 08; //invalid octal - interpreted as 8 Octal literals are invalid when running in strict mode and will cause the JavaScript engine to throw a syntax error. If the fi rst character is a number,plus, or minus, then the conversion goes on to the second character and continues on until either 40 CHAPTER 3 LANGUAGE BASICS ❘ the end of the string is reached or a nonnumeric character is found.

LITERAL MEANING

  The String() function follows these rules: ➤ If the value has a toString() method, it is called (with no arguments) and the result is returned.➤ If the value is null , “null” is returned.➤ If the value is undefined , “undefined” is returned. In the previous example, the constructor is the Object() function.hasOwnProperty(propertyName) — Indicates if the given property exists on the object Each Object instance has the following properties and methods: Instances of Object aren’t very useful on their own, but the concepts are important to understand, because, similar to java.lang.

1. Determine the binary representation of the absolute value (for example, to fi nd –18, fi rst determine the binary representation of 18)

3. Add 1 to the result

  For example, if the number 2 (which is equal to 10 in binary) isshifted 5 bits to the left, the result is 64 (which is equal to 1000000 in binary), as shown here: var oldValue = 2; //equal to binary 10 var newValue = oldValue << 5; //equal to binary 1000000 which is decimal 64LeftShiftExample01.htm Note that when the bits are shifted, fi ve empty bits remain to the right of the number. A value of false converts to 0, whereas a value of true converts to 1.➤ If one operand is a string and the other is a number, attempt to convert the string into a number before checking for equality.➤ If one of the operands is an object and the other is not, the valueOf() method is called on the object to retrieve a primitive value to compare according to the previous rules.

CHAPTER 3 LANGUAGE BASICS If either operand is NaN , the equal operator returns false and the not-equal operator

  Assignment Operators Simple assignment is done with the equal sign ( = ) and simply assigns the value on the right to the variable on the left, as shown in the following example: var num = 10; 68 CHAPTER 3 LANGUAGE BASICS ❘ Compound assignment is done with one of the multiplicative, additive, or bitwise-shift operators followed by an equal sign ( = ). When used in this way, the comma operator always returns the last item in theexpression, as in the following example: var num = (5, 1, 4, 8, 0); //num becomes 0 In this example, num is assigned the value of 0 because it is the last item in the expression.

CHAPTER 3 LANGUAGE BASICS The do-while Statement The do-while statement is a post-test loop, meaning that the escape condition is evaluated only

  It is widely considered a poor practice to use the statement in productionwithcode because of its negative performance impact and the diffi culty in debugging code contained in the statement.with The switch Statement Closely related to the statement is the statement, another fl ow-control statement adopted if switch from other languages. 84 CHAPTER 3 LANGUAGE BASICS ❘➤ There is also a complex data type, Object, that is the base type for all objects in the language.➤ A strict mode places restrictions on certain error-prone parts of the language.➤ ECMAScript provides a lot of the basic operators available in C and other C-like languages, including arithmetic operators, Boolean operators, relational operators, equality operators, and assignment operators.

4 Variables, Scope, and Memory WHAT’S IN THIS CHAPTER?

  Working with primitive and reference values in variables ➤ ➤ Understanding execution context Understanding garbage collection ➤ The nature of variables in JavaScript, as defi ned in ECMA-262, is quite unique compared to that of other languages. Because there are no rules defi ning the type of data that a variable must hold, a variable’s value and data type can change during the lifetime of a script.

PRIMITIVE AND REFERENCE VALUES

  W m There is a deviation in the Internet Explorer implementation of JavaScript through o for url , which becomes part of the function’s context and can, therefore, be returned as thero Internet Explorer 8, where the error caught in a statement is added to the a d fcatchexecution context’s variable object rather than the statement’s variable lo ncatchobject, making it accessible even outside the block. If it fi nds that identifi er name in the local context, then the search stops and the variable is set; if the search doesn’t fi nd the variable name, it continuesalong the scope chain (note that objects in the scope chain also have a prototype chain, so searching may include each object’s prototype chain).

GARBAGE COLLECTION

  For example, the following code cleans up the circular references in the previous example: myObject.element = null; element.someObject = null; Setting a variable to null effectively severs the connection between the variable and the value it previously referenced. ➤ Copying primitive values from one variable to another creates a second copy of the value.➤ Reference values are objects and are stored in memory on the heap.➤ A variable containing a reference value actually contains just a pointer to the object, not the object itself.

5 Reference Types WHAT’S IN THIS CHAPTER?

  Working with objects ➤ ➤ Creating and manipulating arrays Understanding basic JavaScript data types ➤ ➤ Working with primitives and primitive wrappers A reference value (object) is an instance of a specifi c reference type. Consider the following line of code: var person = new Object(); This code creates a new instance of the reference type and stores it in the variable Object .

THE OBJECT TYPE

  A comma is used to separate properties in an object literal, so there’s a comma after the string “Nicholas” but not after the value 29, because age is the last property in the object. It’s also possible to create an object with only the default properties and methods using object literal notation by leaving the space between the curly braces empty, such as this: var person = {}; //same as new Object()person.name = “Nicholas”; person.age = 29; This example is equivalent to the fi rst one in this section, though it looks a little strange.

THE ARRAY TYPE

  The fi rst is to use the Array constructor, as in this line: var colors = new Array(); If you know the number of items that will be in the array, you can pass the count into the constructor, and the length property will automatically be created with that value. If a value is set to an index that is past the end of the array, as with colors[3] in this example, the array length is automatically expanded to be that index plus 1 (so the length becomes 4 in this example because the index being used is 3).

Dokumen baru

Aktifitas terbaru

Download (964 Halaman)
Gratis

Tags

Urban Drainage 3Rd Edition C Primer 3Rd Edition Cn Teaching Mathematics Using Ict 3Rd Edition 03 Algebra And Trigonometry 3Rd Edition Wrede Dan Murray Advanced Calculus 3Rd Edition Html5 And Javascript Web Apps Web Design Competition 3Rd Confest Digital Signal Processing Using Matlab 3Rd Edition Slicer Copy Html5 Programming With Javascript For Dummies
Show more