You are previewing JavaScript : Object-Oriented Programming.
O'Reilly logo
JavaScript : Object-Oriented Programming

Book Description

Build sophisticated web applications by mastering the art of Object-Oriented Javascript

About This Book

  • Learn popular Object-Oriented programming (OOP) principles and design patterns to build robust apps

  • Implement Object-Oriented concepts in a wide range of frontend architectures

  • Capture objects from real-world elements and create object-oriented code that represents them

  • Learn the latest ES6 features and how to test and debug issues with JavaScript code using various modern mechanisms

  • Who This Book Is For

    JavaScript developers looking to enhance their web developments skills by learning object-oriented programming.

    What You Will Learn

  • Get acquainted with the basics of JavaScript language constructs along with object-oriented programming and its application.

  • Learn to build scalable server application in JavaScript using Node.js

  • Generate instances in three programming languages: Python, JavaScript, and C#

  • Work with a combination of access modifiers, prefixes, properties, fields, attributes, and local variables to encapsulate and hide data

  • Master DOM manipulation, cross-browser strategies, and ES6

  • Identify and apply the most common design patterns such as Singleton, Factory, Observer, Model-View-Controller, and Mediator Patterns

  • Design applications using a modular architecture based on SOLID principles

  • In Detail

    JavaScript is the behavior, the third pillar in today's paradigm that looks at web pages as something that consists of : content (HTML), presentation (CSS), and behavior (JavaScript). Using JavaScript, you can create interactive web pages along with desktop widgets, browser, and application extensions, and other pieces of software. Object-oriented programming, which is popularly known as OOP, is basically based on the concept of objects rather than actions.

    The first module will help you master JavaScript and build futuristic web applications. You will start by getting acquainted with the language constructs and how to organize code easily. You develop concrete understanding of variable scoping, loops, and best practices on using types and data structures, as well as the coding style and recommended code organization patterns in JavaScript. The book will also teach you how to use arrays and objects as data structures. By the end of the book, you will understand how reactive JavaScript is going to be the new paradigm.

    The second module is an easy-to-follow course, which includes hands-on examples of solutions to common problems with object-oriented code. It will help to identify objects from real-life scenarios, to protect and hide data with the data encapsulation features of Python, JavaScript, and C#. You will discover the advantage of duck typing in both Python and JavaScript, while you work with interfaces and generics in C#. With a fair understanding of interfaces, multiple inheritance, and composition, you will move on to refactor existing code and to organize your source for easy maintenance and extension.

    The third module takes you through all the in-depth and exciting futures hidden behind the facade. You should read through this course if you want to be able to take your JavaScript skills to a new level of sophistication.

    Style and approach

    This course is a comprehensive guide where each chapter consists of best practices, constructive advice, and few easy-to-follow examples that will build up your skills as you advance through the book. Get object oriented with this course, which takes you on a journey to get acquainted with few useful hands-on tools, features, and ways to enhance your productivity using OOP techniques. The practice questions at the end of each chapter will help you to review what you have understood. It will also act as a reference guide with useful examples on resolving problems with object-oriented code in Python, JavaScript, and C#.

    Downloading the example code for this book. You can download the example code files for all Packt books you have purchased from your account at http://www.PacktPub.com. If you purchased this book elsewhere, you can visit http://www.PacktPub.com/support and register to have the code file.

    Table of Contents

    1. Javascript: Object-Oriented Programming
      1. Table of Contents
      2. Javascript: Object Oriented Programming
      3. Javascript: Object Oriented Programming
      4. Credits
      5. Preface
        1. What this learning path covers
        2. What you need for this learning path
        3. Who this learning path is for
        4. Reader feedback
        5. Customer support
          1. Downloading the example code
          2. Errata
          3. Piracy
          4. Questions
      6. I. Module 1
        1. 1. JavaScript Primer
          1. A little bit of history
          2. How to use this book
          3. Hello World
            1. An overview of JavaScript
              1. Comments
              2. Variables
              3. Constants
              4. Number
              5. String
              6. Undefined values
              7. Booleans
              8. The instanceof operator
              9. Date objects
              10. The + operator
              11. The ++ and -- operators
              12. Boolean operators
              13. Equality
                1. Strict equality using ===
                2. Weak equality using ==
            2. JavaScript types
            3. Automatic semicolon insertion
            4. JavaScript style guide
              1. Whitespaces
              2. Parentheses, line breaks, and braces
              3. Quotes
              4. End of lines and empty lines
              5. Type checking
              6. Type casting
              7. Conditional evaluation
              8. Naming
              9. The eval() method is evil
              10. The strict mode
                1. Enabling the strict mode for an existing code can break it
                2. Package with care
                3. Variables must be declared in strict mode
                  1. The eval() function is cleaner in strict mode
                4. Features that are blocked in strict mode
              11. Running JSHint
          4. Summary
        2. 2. Functions, Closures, and Modules
          1. A function literal
            1. A function declaration
          2. Functions as data
          3. Scoping
            1. Global scope
            2. Local scope
            3. Function-level scope versus block-level scope
            4. Inline function expressions
            5. Block scopes
          4. Function declarations versus function expressions
          5. The arguments parameter
            1. The this parameter
              1. Invocation as a function
              2. Invocation as a method
              3. Invocation as a constructor
              4. Invocation using apply() and call() methods
          6. Anonymous functions
            1. Anonymous functions while creating an object
            2. Anonymous functions while creating a list
            3. Anonymous functions as a parameter to another function
            4. Anonymous functions in conditional logic
          7. Closures
          8. Timers and callbacks
          9. Private variables
          10. Loops and closures
          11. Modules
            1. Stylistic considerations
          12. Summary
        3. 3. Data Structures and Manipulation
          1. Regular expressions
          2. Exact match
          3. Match from a class of characters
          4. Repeated occurrences
            1. Alternatives – OR
          5. Beginning and end
          6. Backreferences
          7. Greedy and lazy quantifiers
          8. Arrays
          9. Maps
          10. Sets
          11. A matter of style
          12. Summary
        4. 4. Object-Oriented JavaScript
          1. Understanding objects
            1. Behavior of JavaScript objects
            2. Prototypes
          2. Instance properties versus prototype properties
          3. Inheritance
          4. Getters and setters
          5. Summary
        5. 5. JavaScript Patterns
          1. Design patterns
          2. The namespace pattern
          3. The module pattern
            1. ES6 modules
          4. The factory pattern
          5. The mixin pattern
          6. The decorator pattern
          7. The observer pattern
          8. JavaScript Model-View-* patterns
            1. Model-View-Controller
            2. Models
            3. Views
            4. Controllers
          9. The Model-View-Presenter pattern
          10. Model-View-ViewModel
          11. Summary
        6. 6. Testing and Debugging
          1. Unit testing
            1. Test-driven development
            2. Behavior-driven development
          2. JavaScript debugging
            1. Syntax errors
            2. Using strict
            3. Runtime exceptions
              1. Console.log and asserts
              2. Chrome DevTools
          3. Summary
        7. 7. ECMAScript 6
          1. Shims or polyfills
          2. Transpilers
          3. ES6 syntax changes
            1. Block scoping
            2. Default parameters
            3. Spread and rest
            4. Destructuring
            5. Object literals
            6. Template literals
            7. Maps and Sets
            8. Symbols
            9. Iterators
            10. For..of loops
            11. Arrow functions
          4. Summary
        8. 8. DOM Manipulation and Events
          1. DOM
            1. Accessing DOM elements
            2. Accessing specific nodes
          2. Chaining
          3. Traversal and manipulation
          4. Working with browser events
          5. Propagation
          6. jQuery event handling and propagation
          7. Event delegation
          8. The event object
          9. Summary
        9. 9. Server-Side JavaScript
          1. An asynchronous evented-model in a browser
          2. Callbacks
          3. Timers
          4. EventEmitters
          5. Modules
            1. Creating modules
          6. npm
            1. Installing packages
          7. JavaScript performance
            1. JavaScript profiling
              1. The CPU profile
              2. The Timeline view
          8. Summary
      7. II. Module 2
        1. 1. Objects Everywhere
          1. Recognizing objects from nouns
          2. Generating blueprints for objects
          3. Recognizing attributes/fields
          4. Recognizing actions from verbs – methods
          5. Organizing the blueprints – classes
          6. Object-oriented approaches in Python, JavaScript, and C#
          7. Summary
        2. 2. Classes and Instances
          1. Understanding classes and instances
          2. Understanding constructors and destructors
          3. Declaring classes in Python
          4. Customizing constructors in Python
          5. Customizing destructors in Python
          6. Creating instances of classes in Python
          7. Declaring classes in C#
          8. Customizing constructors in C#
          9. Customizing destructors in C#
          10. Creating instances of classes in C#
          11. Understanding that functions are objects in JavaScript
          12. Working with constructor functions in JavaScript
          13. Creating instances in JavaScript
          14. Summary
        3. 3. Encapsulation of Data
          1. Understanding the different members of a class
          2. Protecting and hiding data
          3. Working with properties
          4. Understanding the difference between mutability and immutability
          5. Encapsulating data in Python
            1. Adding attributes to a class
            2. Hiding data in Python using prefixes
            3. Using property getters and setters in Python
            4. Using methods to add behaviors to classes in Python
          6. Encapsulating data in C#
            1. Adding fields to a class
            2. Using access modifiers
            3. Using property getters and setters in C#
            4. Working with auto-implemented properties
            5. Using methods to add behaviors to classes in C#
          7. Encapsulating data in JavaScript
            1. Adding properties to a constructor function
            2. Hiding data in JavaScript with local variables
            3. Using property getters and setters in JavaScript
            4. Using methods to add behaviors to constructor functions
          8. Summary
        4. 4. Inheritance and Specialization
          1. Using classes to abstract behavior
          2. Understanding inheritance
          3. Understanding method overloading and overriding
          4. Understanding operator overloading
          5. Taking advantage of polymorphism
          6. Working with simple inheritance in Python
            1. Creating classes that specialize behavior in Python
            2. Using simple inheritance in Python
            3. Overriding methods in Python
            4. Overloading operators in Python
            5. Understanding polymorphism in Python
          7. Working with simple inheritance in C#
            1. Creating classes that specialize behavior in C#
            2. Using simple inheritance in C#
            3. Overloading and overriding methods in C#
            4. Overloading operators in C#
            5. Understanding polymorphism in C#
          8. Working with the prototype-based inheritance in JavaScript
            1. Creating objects that specialize behavior in JavaScript
            2. Using the prototype-based inheritance in JavaScript
            3. Overriding methods in JavaScript
            4. Overloading operators in JavaScript
            5. Understanding polymorphism in JavaScript
          9. Summary
        5. 5. Interfaces, Multiple Inheritance, and Composition
          1. Understanding the requirement to work with multiple base classes
          2. Working with multiple inheritance in Python
            1. Declaring base classes for multiple inheritance
            2. Declaring classes that override methods
            3. Declaring a class with multiple base classes
            4. Working with instances of classes that use multiple inheritance
            5. Working with abstract base classes
          3. Interfaces and multiple inheritance in C#
            1. Declaring interfaces
            2. Declaring classes that implement interfaces
            3. Working with multiple inheritance
            4. Working with methods that receive interfaces as arguments
          4. Working with composition in JavaScript
            1. Declaring base constructor functions for composition
            2. Declaring constructor functions that use composition
            3. Working with an object composed of many objects
            4. Working with instances composed of many objects
          5. Summary
        6. 6. Duck Typing and Generics
          1. Understanding parametric polymorphism and duck typing
          2. Working with duck typing in Python
            1. Declaring a base class that defines the generic behavior
            2. Declaring subclasses for duck typing
            3. Declaring a class that works with duck typing
            4. Using a generic class for multiple types
            5. Working with duck typing in mind
          3. Working with generics in C#
            1. Declaring an interface to be used as a constraint
            2. Declaring an abstract base class that implements two interfaces
            3. Declaring subclasses of an abstract base class
            4. Declaring a class that works with a constrained generic type
            5. Using a generic class for multiple types
            6. Declaring a class that works with two constrained generic types
            7. Using a generic class with two generic type parameters
          4. Working with duck typing in JavaScript
            1. Declaring a constructor function that defines the generic behavior
            2. Working with the prototype chain and duck typing
            3. Declaring methods that work with duck typing
            4. Using generic methods for multiple objects
            5. Working with duck typing in mind
          5. Summary
        7. 7. Organization of Object-Oriented Code
          1. Thinking about the best ways to organize code
          2. Organizing object-oriented code in Python
            1. Working with source files organized in folders
            2. Importing modules
            3. Working with module hierarchies
          3. Organizing object-oriented code in C#
            1. Working with folders
            2. Using namespaces
            3. Working with namespace hierarchies in C#
          4. Organizing object-oriented code in JavaScript
            1. Working with objects to organize code
            2. Declaring constructor functions within objects
            3. Working with nested objects that organize code
          5. Summary
        8. 8. Taking Full Advantage of Object-Oriented Programming
          1. Putting together all the pieces of the object-oriented puzzle
          2. Refactoring existing code in Python
          3. Refactoring existing code in C#
          4. Refactoring existing code in JavaScript
          5. Summary
      8. III. Module 3
        1. 1. Object-oriented JavaScript
          1. A bit of history
            1. Browser wars and renaissance
            2. The present
            3. The future
          2. ECMAScript 5
          3. Object-oriented programming
          4. Setting up your training environment
            1. WebKit's Web Inspector
            2. JavaScriptCore on a Mac
            3. More consoles
          5. Summary
        2. 2. Primitive Data Types, Arrays, Loops, and Conditions
          1. Variables
            1. Variables are case sensitive
          2. Operators
          3. Primitive data types
            1. Finding out the value type – the typeof operator
            2. Numbers
            3. Octal and hexadecimal numbers
            4. Exponent literals
            5. Infinity
              1. NaN
          4. Strings
            1. String conversions
            2. Special strings
          5. Booleans
          6. Logical operators
            1. Operator precedence
            2. Lazy evaluation
          7. Comparison
            1. Undefined and null
          8. Primitive data types recap
          9. Arrays
            1. Adding/updating array elements
            2. Deleting elements
            3. Arrays of arrays
          10. Conditions and loops
            1. The if condition
            2. The else clause
          11. Code blocks
            1. Checking if a variable exists
            2. Alternative if syntax
          12. Switch
          13. Loops
            1. While loops
              1. Do-while loops
            2. For loops
            3. For-in loops
          14. Comments
          15. Summary
          16. Exercises
        3. 3. Functions
          1. What is a function?
            1. Calling a function
            2. Parameters
            3. Predefined functions
              1. parseInt()
              2. parseFloat()
              3. isNaN()
              4. isFinite()
                1. Encode/decode URIs
              5. eval()
                1. A bonus – the alert() function
          2. Scope of variables
            1. Variable hoisting
          3. Functions are data
            1. Anonymous functions
            2. Callback functions
              1. Callback examples
            3. Immediate functions
            4. Inner (private) functions
            5. Functions that return functions
            6. Function, rewrite thyself!
          4. Closures
            1. Scope chain
            2. Breaking the chain with a closure
              1. Closure #1
              2. Closure #2
              3. A definition and closure #3
            3. Closures in a loop
            4. Getter/setter
            5. Iterator
          5. Summary
          6. Exercises
        4. 4. Objects
          1. From arrays to objects
            1. Elements, properties, methods, and members
            2. Hashes and associative arrays
            3. Accessing an object's properties
            4. Calling an object's methods
            5. Altering properties/methods
            6. Using the this value
            7. Constructor functions
            8. The global object
            9. The constructor property
            10. The instanceof operator
            11. Functions that return objects
            12. Passing objects
            13. Comparing objects
            14. Objects in the WebKit console
              1. console.log
          2. Built-in objects
            1. Object
            2. Array
              1. A few array methods
            3. Function
              1. Properties of function objects
                1. Prototype
              2. Methods of function objects
                1. Call and apply
              3. The arguments object revisited
              4. Inferring object types
            4. Boolean
            5. Number
            6. String
              1. A few methods of string objects
            7. Math
            8. Date
              1. Methods to work with date objects
                1. Calculating birthdays
            9. RegExp
              1. Properties of RegExp objects
              2. Methods of RegExp objects
              3. String methods that accept regular expressions as arguments
              4. search() and match()
              5. replace()
              6. Replace callbacks
              7. split()
              8. Passing a string when a RegExp is expected
              9. Error objects
          3. Summary
          4. Exercises
        5. 5. Prototype
          1. The prototype property
            1. Adding methods and properties using the prototype
          2. Using the prototype's methods and properties
            1. Own properties versus prototype properties
            2. Overwriting a prototype's property with an own property
              1. Enumerating properties
            3. isPrototypeOf()
            4. The secret __proto__ link
          3. Augmenting built-in objects
            1. Augmenting built-in objects – discussion
            2. Prototype gotchas
          4. Summary
          5. Exercises
        6. 6. Inheritance
          1. Prototype chaining
            1. Prototype chaining example
            2. Moving shared properties to the prototype
          2. Inheriting the prototype only
            1. A temporary constructor – new F()
          3. Uber – access to the parent from a child object
          4. Isolating the inheritance part into a function
          5. Copying properties
          6. Heads-up when copying by reference
          7. Objects inherit from objects
          8. Deep copy
          9. object()
          10. Using a mix of prototypal inheritance and copying properties
          11. Multiple inheritance
            1. Mixins
          12. Parasitic inheritance
          13. Borrowing a constructor
            1. Borrow a constructor and copy its prototype
          14. Summary
          15. Case study – drawing shapes
            1. Analysis
            2. Implementation
            3. Testing
          16. Exercises
        7. 7. The Browser Environment
          1. Including JavaScript in an HTML page
          2. BOM and DOM – an overview
          3. BOM
            1. The window object revisited
            2. window.navigator
            3. Your console is a cheat sheet
            4. window.location
            5. window.history
            6. window.frames
            7. window.screen
            8. window.open()/close()
            9. window.moveTo() and window.resizeTo()
            10. window.alert(), window.prompt(), and window.confirm()
            11. window.setTimeout() and window.setInterval()
            12. window.document
          4. DOM
            1. Core DOM and HTML DOM
            2. Accessing DOM nodes
              1. The document node
              2. documentElement
              3. Child nodes
              4. Attributes
              5. Accessing the content inside a tag
              6. DOM access shortcuts
              7. Siblings, body, first, and last child
              8. Walk the DOM
            3. Modifying DOM nodes
              1. Modifying styles
              2. Fun with forms
            4. Creating new nodes
              1. DOM-only method
              2. cloneNode()
              3. insertBefore()
            5. Removing nodes
            6. HTML-only DOM objects
              1. Primitive ways to access the document
              2. document.write()
              3. Cookies, title, referrer, domain
          5. Events
            1. Inline HTML attributes
            2. Element Properties
            3. DOM event listeners
            4. Capturing and bubbling
            5. Stop propagation
            6. Prevent default behavior
            7. Cross-browser event listeners
            8. Types of events
          6. XMLHttpRequest
            1. Sending the request
            2. Processing the response
            3. Creating XMLHttpRequest objects in IE prior to Version 7
            4. A is for Asynchronous
            5. X is for XML
            6. An example
          7. Summary
          8. Exercises
        8. 8. Coding and Design Patterns
          1. Coding patterns
            1. Separating behavior
              1. Content
              2. Presentation
              3. Behavior
              4. Example of separating behavior
              5. Asynchronous JavaScript loading
            2. Namespaces
              1. An Object as a namespace
              2. Namespaced constructors
              3. A namespace() method
            3. Init-time branching
            4. Lazy definition
            5. Configuration object
            6. Private properties and methods
            7. Privileged methods
            8. Private functions as public methods
            9. Immediate functions
            10. Modules
            11. Chaining
            12. JSON
          2. Design patterns
            1. Singleton
            2. Singleton 2
              1. Global variable
              2. Property of the Constructor
              3. In a private property
            3. Factory
            4. Decorator
              1. Decorating a Christmas tree
            5. Observer
          3. Summary
        9. 9. Reserved Words
          1. Keywords
          2. Future reserved words
          3. Previously reserved words
        10. 10. Built-in Functions
        11. 11. Built-in Objects
          1. Object
            1. Members of the Object constructor
            2. The Object.prototype members
            3. ECMAScript 5 additions to Object
          2. Array
            1. The Array.prototype members
            2. ECMAScript 5 additions to Array
          3. Function
            1. The Function.prototype members
            2. ECMAScript 5 additions to a function
          4. Boolean
          5. Number
            1. Members of the Number constructor
            2. The Number.prototype members
          6. String
            1. Members of the String constructor
            2. The String.prototype members
            3. ECMAScript 5 additions to String
          7. Date
            1. Members of the Date constructor
            2. The Date.prototype members
            3. ECMAScript 5 additions to Date
          8. Math
            1. Members of the Math object
          9. RegExp
            1. The RegExp.prototype members
          10. Error objects
            1. The Error.prototype members
          11. JSON
            1. Members of the JSON object
        12. 12. Regular Expressions
      9. A. Biblography
      10. Index