Object-Oriented JavaScript
3.5/5
()
About this ebook
JavaScript is the behavior, the third pillar in today's paradigm that looks at web pages as something that consists of clearly distinguishable parts: content (HTML), presentation (CSS) and behavior (JavaScript). Using JavaScript, you can create not only web pages but also desktop widgets, browser and application extensions, and other pieces of software. It's a pretty good deal: you learn one language and then code all kinds of different applications. While there's one chapter specifically dedicated to the web browser environment including DOM, Events and AJAX tutorials, the rest is applicable to the other environments
Many web developers have tried coding or adopting some bits of JavaScript, but it is time to "man up" and learn the language properly because it is the language of the browser and is, virtually, everywhere. This book starts from zero, not assuming any prior JavaScript programming knowledge and takes you through all the in-depth and exciting futures hidden behind the facade.
Once listed in the "nice to have" sections of job postings, these days the knowledge of JavaScript is a deciding factor when it comes to hiring web developers. After reading this book you'll be prepared to ace your JavaScript job interview and even impress with some bits that the interviewer maybe didn't know. You should read this book if you want to be able to take your JavaScript skills to a new level of sophistication.
ApproachYou will first be introduced to object-oriented programming, then to the basics of objects in JavaScript. This book takes a do-it-yourself approach when it comes to writing code, because the best way to really learn a programming language is by writing code. You are encouraged to type code into Firebug's console, see how it works and then tweak it and play around with it. There are practice questions at the end of each chapter to help you review what you have learned.
Who this book is forFor new to intermediate JavaScript developer who wants to prepare themselves for web development problems solved by smart JavaScript!
Stoyan Stefanov
Stoyan Stefanov is a Facebook engineer. Previously at Yahoo, he was the creator of the smush.it online image-optimization tool and architect of the YSlow 2.0 performance tool. Stoyan is the author of JavaScript Patterns and Object-Oriented JavaScript, as well as a contributor to Even Faster Web Sites and High-Performance JavaScript. Additionally, he’s a blogger (phpied.com) and frequent speaker at conferences like Velocity, JSConf, and Fronteers.
Read more from Stoyan Stefanov
Object-Oriented JavaScript: Create scalable, reusable high-quality JavaScript applications, and libraries Rating: 3 out of 5 stars3/5Object-Oriented JavaScript - Third Edition Rating: 4 out of 5 stars4/5JavaScript : Object-Oriented Programming Rating: 0 out of 5 stars0 ratings
Related to Object-Oriented JavaScript
Related ebooks
Mastering JavaScript Rating: 4 out of 5 stars4/5Practical Web Development Rating: 5 out of 5 stars5/5Learning Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsDjango Design Patterns and Best Practices Rating: 5 out of 5 stars5/5Mastering JavaScript Single Page Application Development Rating: 0 out of 5 stars0 ratingsFunctional Python Programming Rating: 0 out of 5 stars0 ratingsThe PHP Workshop: Learn to build interactive applications and kickstart your career as a web developer Rating: 0 out of 5 stars0 ratings.NET Design Patterns Rating: 3 out of 5 stars3/5JavaScript Enlightenment Rating: 4 out of 5 stars4/5Learning JavaScript Data Structures and Algorithms Rating: 5 out of 5 stars5/5Clean Code in JavaScript: Develop reliable, maintainable, and robust JavaScript Rating: 5 out of 5 stars5/5Professional JavaScript for Web Developers Rating: 0 out of 5 stars0 ratingsJavaScript: Advanced Guide to Programming Code with JavaScript Rating: 0 out of 5 stars0 ratings50 Recipes for Programming Node.js Rating: 3 out of 5 stars3/5JavaScript Unlocked Rating: 5 out of 5 stars5/5Responsive Web Design with HTML5 and CSS3 - Second Edition Rating: 4 out of 5 stars4/5Mastering JavaScript Design Patterns Rating: 4 out of 5 stars4/5React: Building Modern Web Applications Rating: 5 out of 5 stars5/5Mastering JavaScript Object-Oriented Programming Rating: 0 out of 5 stars0 ratingsLearning JavaScript Data Structures and Algorithms - Second Edition Rating: 0 out of 5 stars0 ratingsJavaScript and JSON Essentials Rating: 5 out of 5 stars5/5Learn JavaScript in 24 Hours Rating: 3 out of 5 stars3/5Learning jQuery Rating: 4 out of 5 stars4/5React.js Essentials Rating: 4 out of 5 stars4/5ReactJS by Example - Building Modern Web Applications with React Rating: 4 out of 5 stars4/5HTML5 and CSS3: Building Responsive Websites Rating: 0 out of 5 stars0 ratings50 Recipes for Programming CSS3 Rating: 0 out of 5 stars0 ratingsJavascript For Beginners: Your Guide For Learning Javascript Programming in 24 Hours Rating: 3 out of 5 stars3/5Responsive Web Design with HTML5 and CSS3 Essentials Rating: 5 out of 5 stars5/5
Internet & Web For You
How to Be Invisible: Protect Your Home, Your Children, Your Assets, and Your Life Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Coding For Dummies Rating: 5 out of 5 stars5/5No Place to Hide: Edward Snowden, the NSA, and the U.S. Surveillance State Rating: 4 out of 5 stars4/5How to Disappear and Live Off the Grid: A CIA Insider's Guide Rating: 0 out of 5 stars0 ratingsSocial Engineering: The Science of Human Hacking Rating: 3 out of 5 stars3/5The Hacker Crackdown: Law and Disorder on the Electronic Frontier Rating: 4 out of 5 stars4/5Podcasting For Dummies Rating: 4 out of 5 stars4/5The Gothic Novel Collection Rating: 5 out of 5 stars5/5How To Start A Profitable Authority Blog In Under One Hour Rating: 5 out of 5 stars5/5Mike Meyers' CompTIA Security+ Certification Guide, Third Edition (Exam SY0-601) Rating: 5 out of 5 stars5/5Remote/WebCam Notarization : Basic Understanding Rating: 3 out of 5 stars3/5HTML in 30 Pages Rating: 5 out of 5 stars5/5Tor and the Dark Art of Anonymity Rating: 5 out of 5 stars5/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsSix Figure Blogging Blueprint Rating: 5 out of 5 stars5/5The Digital Marketing Handbook: A Step-By-Step Guide to Creating Websites That Sell Rating: 5 out of 5 stars5/5How To Make Money Blogging: How I Replaced My Day-Job With My Blog and How You Can Start A Blog Today Rating: 4 out of 5 stars4/5Wordpress for Beginners: The Easy Step-by-Step Guide to Creating a Website with WordPress Rating: 5 out of 5 stars5/5The Beginner's Affiliate Marketing Blueprint Rating: 4 out of 5 stars4/5Everybody Lies: Big Data, New Data, and What the Internet Can Tell Us About Who We Really Are Rating: 4 out of 5 stars4/5Beginner's Guide To Starting An Etsy Print-On-Demand Shop Rating: 0 out of 5 stars0 ratingsAn Ultimate Guide to Kali Linux for Beginners Rating: 3 out of 5 stars3/5The Cyber Attack Survival Manual: Tools for Surviving Everything from Identity Theft to the Digital Apocalypse Rating: 0 out of 5 stars0 ratingsWireless Hacking 101 Rating: 5 out of 5 stars5/5The $1,000,000 Web Designer Guide: A Practical Guide for Wealth and Freedom as an Online Freelancer Rating: 5 out of 5 stars5/5
Reviews for Object-Oriented JavaScript
12 ratings2 reviews
- Rating: 3 out of 5 stars3/5This book is not for beginners because the author does not really explain why certain parts of the code work as it does. He does this especially when providing examples of the code. However, if you have been studying JavaScript for a while and have an intermediate understanding of the language, then this book will be perfect for you.
- Rating: 4 out of 5 stars4/5This is a very good one, some chapters are very impressive, for the number of approaches being described to solve the same requirements but also for the simplicity of the language. For example the chapters on object inheritance and prototype are great as well as the section on closures is probably the best description of Javascript closures I read.Only a small section of the last chapter is pretty disappointing given that I am mostly a software designer, the design patterns section. For example writing that a javascript object literal is like a singleton is just meaningless and misleading. A design pattern is a (design) problem frame, not a label and not a description of a cloneable solution. The proposed solutions are probably the least important part of a pattern, identification criteria and problem frame are the most important.For the rest the book is definitely one of the best core Javascript guides you can find.
1 person found this helpful
Book preview
Object-Oriented JavaScript - Stoyan Stefanov
Table of Contents
Object-Oriented JavaScript Second Edition
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Support files, eBooks, discount offers and more
Why Subscribe?
Free Access for Packt account holders
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Errata
Piracy
Questions
1. Object-oriented JavaScript
A bit of history
Browser wars and renaissance
The present
The future
ECMAScript 5
Object-oriented programming
Objects
Classes
Encapsulation
Aggregation
Inheritance
Polymorphism
OOP summary
Setting up your training environment
WebKit's Web Inspector
JavaScriptCore on a Mac
More consoles
Summary
2. Primitive Data Types, Arrays, Loops, and Conditions
Variables
Variables are case sensitive
Operators
Primitive data types
Finding out the value type – the typeof operator
Numbers
Octal and hexadecimal numbers
Exponent literals
Infinity
NaN
Strings
String conversions
Special strings
Booleans
Logical operators
Operator precedence
Lazy evaluation
Comparison
Undefined and null
Primitive data types recap
Arrays
Adding/updating array elements
Deleting elements
Arrays of arrays
Conditions and loops
The if condition
The else clause
Code blocks
Checking if a variable exists
Alternative if syntax
Switch
Loops
While loops
Do-while loops
For loops
For-in loops
Comments
Summary
Exercises
3. Functions
What is a function?
Calling a function
Parameters
Predefined functions
parseInt()
parseFloat()
isNaN()
isFinite()
Encode/decode URIs
eval()
A bonus – the alert() function
Scope of variables
Variable hoisting
Functions are data
Anonymous functions
Callback functions
Callback examples
Immediate functions
Inner (private) functions
Functions that return functions
Function, rewrite thyself!
Closures
Scope chain
Breaking the chain with a closure
Closure #1
Closure #2
A definition and closure #3
Closures in a loop
Getter/setter
Iterator
Summary
Exercises
4. Objects
From arrays to objects
Elements, properties, methods, and members
Hashes and associative arrays
Accessing an object's properties
Calling an object's methods
Altering properties/methods
Using the this value
Constructor functions
The global object
The constructor property
The instanceof operator
Functions that return objects
Passing objects
Comparing objects
Objects in the WebKit console
console.log
Built-in objects
Object
Array
A few array methods
Function
Properties of function objects
Prototype
Methods of function objects
Call and apply
The arguments object revisited
Inferring object types
Boolean
Number
String
A few methods of string objects
Math
Date
Methods to work with date objects
Calculating birthdays
RegExp
Properties of RegExp objects
Methods of RegExp objects
String methods that accept regular expressions as arguments
search() and match()
replace()
Replace callbacks
split()
Passing a string when a RegExp is expected
Error objects
Summary
Exercises
5. Prototype
The prototype property
Adding methods and properties using the prototype
Using the prototype's methods and properties
Own properties versus prototype properties
Overwriting a prototype's property with an own property
Enumerating properties
isPrototypeOf()
The secret __proto__ link
Augmenting built-in objects
Augmenting built-in objects – discussion
Prototype gotchas
Summary
Exercises
6. Inheritance
Prototype chaining
Prototype chaining example
Moving shared properties to the prototype
Inheriting the prototype only
A temporary constructor – new F()
Uber – access to the parent from a child object
Isolating the inheritance part into a function
Copying properties
Heads-up when copying by reference
Objects inherit from objects
Deep copy
object()
Using a mix of prototypal inheritance and copying properties
Multiple inheritance
Mixins
Parasitic inheritance
Borrowing a constructor
Borrow a constructor and copy its prototype
Summary
Case study – drawing shapes
Analysis
Implementation
Testing
Exercises
7. The Browser Environment
Including JavaScript in an HTML page
BOM and DOM – an overview
BOM
The window object revisited
window.navigator
Your console is a cheat sheet
window.location
window.history
window.frames
window.screen
window.open()/close()
window.moveTo() and window.resizeTo()
window.alert(), window.prompt(), and window.confirm()
window.setTimeout() and window.setInterval()
window.document
DOM
Core DOM and HTML DOM
Accessing DOM nodes
The document node
documentElement
Child nodes
Attributes
Accessing the content inside a tag
DOM access shortcuts
Siblings, body, first, and last child
Walk the DOM
Modifying DOM nodes
Modifying styles
Fun with forms
Creating new nodes
DOM-only method
cloneNode()
insertBefore()
Removing nodes
HTML-only DOM objects
Primitive ways to access the document
document.write()
Cookies, title, referrer, domain
Events
Inline HTML attributes
Element Properties
DOM event listeners
Capturing and bubbling
Stop propagation
Prevent default behavior
Cross-browser event listeners
Types of events
XMLHttpRequest
Sending the request
Processing the response
Creating XMLHttpRequest objects in IE prior to Version 7
A is for Asynchronous
X is for XML
An example
Summary
Exercises
8. Coding and Design Patterns
Coding patterns
Separating behavior
Content
Presentation
Behavior
Example of separating behavior
Asynchronous JavaScript loading
Namespaces
An Object as a namespace
Namespaced constructors
A namespace() method
Init-time branching
Lazy definition
Configuration object
Private properties and methods
Privileged methods
Private functions as public methods
Immediate functions
Modules
Chaining
JSON
Design patterns
Singleton
Singleton 2
Global variable
Property of the Constructor
In a private property
Factory
Decorator
Decorating a Christmas tree
Observer
Summary
A. Reserved Words
Keywords
Future reserved words
Previously reserved words
B. Built-in Functions
C. Built-in Objects
Object
Members of the Object constructor
The Object.prototype members
ECMAScript 5 additions to Object
Array
The Array.prototype members
ECMAScript 5 additions to Array
Function
The Function.prototype members
ECMAScript 5 additions to a function
Boolean
Number
Members of the Number constructor
The Number.prototype members
String
Members of the String constructor
The String.prototype members
ECMAScript 5 additions to String
Date
Members of the Date constructor
The Date.prototype members
ECMAScript 5 additions to Date
Math
Members of the Math object
RegExp
The RegExp.prototype members
Error objects
The Error.prototype members
JSON
Members of the JSON object
D. Regular Expressions
Index
Object-Oriented JavaScript Second Edition
Object-Oriented JavaScript Second Edition
Copyright © 2013 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
Production Reference: 1190713
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-84969-312-7
www.packtpub.com
Cover Image by Gorkee Bhardwaj (<afterglowpictures@gmail.com>)
Credits
Authors
Stoyan Stefanov
Kumar Chetan Sharma
Reviewers
Kumar Chetan Sharma
Alex R. Young
Acquisition Editors
Martin Bell
Jonathan Titmus
Lead Technical Editor
Arun Nadar
Technical Editors
Prasad Dalvi
Mausam Kothari
Worrell Lewis
Amit Ramadas
Project Coordinator
Leena Purkait
Proofreaders
Paul Hindle
Linda Morris
Indexer
Rekha Nair
Graphics
Ronak Dhruv
Production Coordinator
Arvindkumar Gupta
Cover Work
Arvindkumar Gupta
About the Authors
Stoyan Stefanov is a Facebook engineer, author, and speaker. He talks regularly about web development topics at conferences and his blog www.phpied.com, and 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.
To my reviewers who volunteered their time reviewing drafts of this book and whom I deeply respect and look up to: a big thank you for your invaluable inputs.
Kumar Chetan Sharma studied to be an electronics engineer and has always wanted to build an ultimate sound system. He then, by chance, got a part time job as a trainee HTML guy. From there he picked up CSS and JavaScript and there was no looking back. It was the time when JavaScript was used to validate forms or create fancy DHTML effects and IE6 was the only browser the world knew. He has been developing web applications since then, using LAMP stack. He has worked on white label social networking applications to web control panels for telecom and networked electrical charger infrastructures. He currently works as a frontend engineer for Yahoo! Search.
About the Reviewer
Alex R. Young is an engineering graduate with over 10 years of web and mobile industry experience.
He's the editor-in-chief of DailyJS, and writes regularly about all things JavaScript. He has also worked for major multinational corporations, including Thomson Reuters, and is currently writing a book about Node.
www.PacktPub.com
Support files, eBooks, discount offers and more
You might want to visit www.PacktPub.com for support files and downloads related to your book.
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
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.
http://PacktLib.PacktPub.com
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can access, read and search across Packt's entire library of books.
Why Subscribe?
Fully searchable across every book published by Packt
Copy and paste, print and bookmark content
On demand and accessible via web browser
Free Access for Packt account holders
If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view nine entirely free books. Simply use your login credentials for immediate access.
Preface
This is the second edition of the highly rated book Object-Oriented JavaScript by Stoyan Stefanov, Packt Publishing. After the release of the first edition, in the last five years, JavaScript has moved from being mostly used in browsers for client-side technologies to being used even on server side. This edition explores the language side
of JavaScript. The stress is on the standards part of the language. The book talks about ECMA Script, Object-Oriented JS, patterns, prototypal inheritance, and design patterns.
The 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. Exercises at the end of the chapters help you assess your understanding.
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 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 learn to master them all. You 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, Prototype, is dedicated to the all-important concept of prototypes in JavaScript. It also explains how prototype chain works, hasOwnProperty(), and some gotchas of prototypes.
Chapter 6, Inheritance, discusses how inheritance works. This chapter also talks about a method to create subclasses like other classic languages.
Chapter 7, The Browser Environment, is dedicated to browsers. This chapter also covers BOM (Browser Object Model), DOM (W3C's Document Object Model), browser events, and AJAX.
Chapter 8, Coding and Design Patterns, dives into various unique JavaScript coding patterns, as well as several language-independent design patterns, translated to JavaScript from the Book of Four, the most influential work of software design patterns. The chapter also discusses JSON.
Appendix A, Reserved Words, lists the reserved words in JavaScript.
Appendix B, Built-in Functions, is a reference of built-in JavaScript functions together with sample uses.
Appendix C, Built-in Objects, is a reference that provides details and examples of the use of every method and property of every built-in object in JavaScript.
Appendix D, Regular Expressions, is a regular expressions pattern reference.
Appendix E, Answers to Exercise Questions, has solutions for all the exercises mentioned at the end of the chapters.
You can download this Appendix from http://www.packtpub.com/sites/default/files/downloads/3127OT_Answers_to_Exercise_Questions.pdf.
What you need for this book
You need a modern browser—Google Chrome or Firefox are recommended—and an optional Node.js setup. The latest version of Firefox comes with web developer tools, but Firebug is highly recommended. To edit JavaScript you can use any text editor of your choice.
Who this book is for
This book is for anyone who is starting to learn JavaScript or who knows JavaScript but isn't very good at the object-oriented part of it.
Conventions
In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.
Code words in text are shown as follows: If you want to be sure, you can check the cancellable property of the event object
.
A block of code will be set as follows:
var a;
var thisIsAVariable;
var _and_this_too;
var mix12three;
When we wish to draw your attention to an output of a code block, the relevant lines or items will be shown in bold:
> var case_matters = 'lower';
> var CASE_MATTERS = 'upper';
> case_matters;
lower
> CASE_MATTERS;
upper
Any command-line input or output is written as follows:
alias jsc='/System/Library/Frameworks/JavaScriptCore.framework/Versions/Current/Resources/jsc'
New terms and important words are introduced in a bold-type font. Words that you see on the screen, in menus or dialog boxes for example, appear in our text like this: If the user clicks on Cancel, the preventDefault() method is called
.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.
To send us general feedback, simply send an e-mail to <feedback@packtpub.com>, and mention the book title via the subject of your message.
If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide on www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the errata submission form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title. Any existing errata can be viewed by selecting your title from http://www.packtpub.com/support.
Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at <copyright@packtpub.com> with a link to the suspected pirated material.
We appreciate your help in protecting our authors, and our ability to bring you valuable content.
Questions
You can contact us at <questions@packtpub.com> if you are having a problem with any aspect of the book, and we will do our best to address it.
Chapter 1. Object-oriented JavaScript
Ever since the early days of the Web, there has been a need for more dynamic and responsive interfaces. While it's OK to read static HTML pages of text and even better when they are beautifully presented with the help of CSS, it's much more fun to engage with applications in our browsers, such as e-mail, calendars, banking, shopping, drawing, playing games, and text editing. All that is possible thanks to JavaScript, the programming language of the Web. JavaScript started with simple one-liners embedded in HTML, but is now used in much more sophisticated ways. Developers leverage the object-oriented nature of the language to build scalable code architectures made up of reusable pieces.
If you look at the past and present buzzwords in web development—DHTML, Ajax, Web 2.0, HTML5—they all essentially mean HTML, CSS, and JavaScript. HTML for content, CSS for presentation, and JavaScript for behavior. In other words, JavaScript is the glue that makes everything work together so that we can build rich web applications.
But that's not all, JavaScript can be used for more than just the Web.
JavaScript programs run inside a host environment. The web browser is the most common environment, but it's not the only one. Using JavaScript, you can create all kinds of widgets, application extensions, and other pieces of software, as you'll see in a bit. Taking the time to learn JavaScript is a smart investment; you learn one language and can then write all kinds of different applications running on multiple platforms, including mobile and server-side applications. These days, it's safe to say that JavaScript is everywhere.
This book starts from zero, and does not assume any prior programming knowledge other than some basic understanding of HTML. Although there is one chapter dedicated to the web browser environment, the rest of the book is about JavaScript in general, so it's applicable to all environments.
Let's start with the following:
A brief introduction to the story behind JavaScript
The basic concepts you'll encounter in discussions on object-oriented programming
A bit of history
Initially, the Web was not much more than just a number of scientific publications in the form of static HTML documents connected together with hyperlinks. Believe it or not, there was a time when there was no way to put an image in a page. But that soon changed. As the Web grew in popularity and size, the webmasters who were creating HTML pages felt they needed something more. They wanted to create richer user interactions, mainly driven by the desire to save server roundtrips for simple tasks such as form validation. Two options came up: Java applets and LiveScript, a language conceived by Brendan Eich at Netscape in 1995 and later included in the Netscape 2.0 browser under the name of JavaScript.
The applets didn't quite catch on, but JavaScript did. The ability to use short code snippets embedded in HTML documents and alter otherwise static elements of a web page was embraced by the webmaster community. Soon, the competing browser vendor Microsoft shipped Internet Explorer (IE) 3.0 with JScript, which was a reverse engineered version of JavaScript plus some IE-specific features. Eventually, there was an effort to standardize the various implementations of the language, and this is how ECMAScript was born. ECMA (European Computer Manufacturers Association ) created the standard called ECMA-262, which describes the core parts of the JavaScript programming language without browser and web page-specific features.
You can think of JavaScript as a term that encompasses three pieces:
ECMAScript—the core language—variables, functions, loops, and so on. This part is independent of the browser and this language can be used in many other environments.
Document Object Model (DOM), which provides ways to work with HTML and XML documents. Initially, JavaScript provided limited access to what's scriptable on the page, mainly forms, links, and images. Later it was expanded to make all elements scriptable. This lead to the creation of the DOM standard by the World Wide Web Consortium (W3C) as a language-independent (no longer tied to JavaScript) way to manipulate structured documents.
Browser Object Model (BOM), which is a set of objects related to the browser environment and was never part of any standard until HTML5 started standardizing some of the common objects that exist across browsers.
While there is one chapter in the book dedicated to the browser, the DOM, and the BOM, most of the book describes the core language and teaches you skills you can use in any environment where JavaScript programs run.
Browser wars and renaissance
For better or for worse, JavaScript's instant popularity happened during the period of the Browser Wars I (approximately 1996 to 2001). Those were the times during the initial Internet boom when the two major browser vendors—Netscape and Microsoft—were competing for market share. Both were constantly adding more bells and whistles to their browsers and their versions of JavaScript, DOM, and BOM, which naturally led to many inconsistencies. While adding more features, the browser vendors were falling behind on providing proper development and debugging tools and adequate documentation. Often, development was a pain; you would write a script while testing in one browser, and once you're done with development, you test in the other browser, only to find that your script simply fails for no apparent reason and the best you can get is a cryptic error message like Operation aborted
.
Inconsistent implementations, missing documentation, and no appropriate tools painted JavaScript in such a light that many programmers simply refused to bother with it.
On the other hand, developers who did try to experiment with JavaScript got a little carried away adding too many special effects to their pages without much regard of how usable the end results were. Developers were eager to make use of every new possibility the browsers provided and ended up enhancing
their web pages with things like animations in the status bar, flashing colors, blinking texts, objects stalking your mouse cursor, and many other innovations
that actually hurt the user experience. These various ways to abuse JavaScript are now mostly gone, but they were one of the reasons why the language got some bad reputation. Many serious
programmers dismissed JavaScript as nothing but a toy for designers to play around with, and dismissed it as a language unsuitable for serious applications. The JavaScript backlash caused some web projects to completely ban any client-side programming and trust only their predictable and tightly controlled server. And really, why would you double the time to deliver a finished product and then spend additional time debugging problems with the different browsers?
Everything changed in the years following the end of the Browser Wars I. A number of events reshaped the web development landscape in a positive way. Some of them are given as follows:
Microsoft won the war with the introduction of IE6, the best browser at the time, and for many years they stopped developing Internet Explorer. This allowed time for other browsers to catch up and even surpass IE's capabilities.
The movement for web standards was embraced by developers and browser vendors alike. Naturally, developers didn't like having to code everything two (or more) times to account for browsers' differences; therefore, they liked the idea of having agreed-upon standards that everyone would follow.
Developers and technologies matured and more people started caring about things like usability, progressive enhancement techniques, and accessibility. Tools such as Firebug made developers much more productive and the development less of a