Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Mastering JavaScript Object-Oriented Programming
Mastering JavaScript Object-Oriented Programming
Mastering JavaScript Object-Oriented Programming
Ebook534 pages4 hours

Mastering JavaScript Object-Oriented Programming

Rating: 0 out of 5 stars

()

Read preview

About this ebook

About This Book
  • Covering all the new Object-Oriented features introduced in ES6, this book shows you how to build large-scale web apps
  • Build apps that promote scalability, maintainability, and reusability
  • Learn popular Object-Oriented programming (OOP) principles and design patterns to build robust apps
  • Implement Object-Oriented concepts in a wide range of front-end architectures
Who This Book Is For

This book is ideal for you if you are a JavaScript developer who wants to gain expertise in OOP with JavaScript to improve your web development skills and build professional quality web applications.

LanguageEnglish
Release dateJun 29, 2016
ISBN9781785888267
Mastering JavaScript Object-Oriented Programming

Read more from Andrea Chiarelli

Related to Mastering JavaScript Object-Oriented Programming

Related ebooks

Programming For You

View More

Related articles

Reviews for Mastering JavaScript Object-Oriented Programming

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Mastering JavaScript Object-Oriented Programming - Andrea Chiarelli

    Table of Contents

    Mastering JavaScript Object-Oriented Programming

    Credits

    About the Author

    About the Reviewer

    www.PacktPub.com

    eBooks, discount offers, and more

    Why subscribe?

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. A Refresher of Objects

    Object literals

    Properties

    Methods

    Object constructors

    The Object() constructor

    Object prototypes

    Using classes

    Summary

    2. Diving into OOP Principles

    OOP principles

    Is JavaScript Object Oriented?

    Abstraction and modeling support

    Association

    Aggregation

    Composition

    OOP principles support

    Encapsulation

    Inheritance

    Polymorphism

    JavaScript OOP versus classical OOP

    Summary

    3. Working with Encapsulation and Information Hiding

    Encapsulation and information hiding

    Convention-based approach

    Privacy levels using closure

    Scope and closure

    Privacy levels

    Benefits and drawbacks

    A meta-closure approach

    Immediately invoked function expressions

    Creating a meta-closure with an IIFE

    Managing isolated private members

    A definitive solution with WeakMaps

    Property descriptors

    Controlling access to public properties

    Using getters and setters

    Describing properties

    Properties with internal state

    Information hiding in ES6 classes

    Summary

    4. Inheriting and Creating Mixins

    Why inheritance?

    Objects and prototypes

    What is a prototype?

    Creating objects

    Prototype chaining

    Inheritance and constructors

    ES6 inheritance

    Controlling inheritance

    Overriding methods

    Overriding properties

    Protected members

    Preventing extensions

    Implementing multiple inheritance

    Creating and using mixins

    Mixing prototypes

    Mixing classes

    Summary

    5. Defining Contracts with Duck Typing

    Managing dynamic typing

    Dynamic data types

    Data typing and objects

    From data type to instance type

    Beyond the instance type

    Contracts and interfaces

    Duck typing

    A basic approach

    A general solution

    Emulating Interfaces with duck typing

    Multiple interface implementation

    Duck typing and polymorphism

    Summary

    6. Advanced Object Creation

    Creating objects

    Design patterns and object creation

    Creating a singleton

    The mysterious behavior of constructors

    Singletons

    When to use singletons?

    An object factory

    Understanding factories

    Factory with constructor registration

    The abstract factory

    The builder pattern

    When to use the builder pattern?

    Comparing factory and builder patterns

    Recycling objects with an object pool

    Summary

    7. Presenting Data to the User

    Managing user interfaces

    The user interface problems

    User interfaces and JavaScript

    Presentation patterns

    Model, View, and Controller

    The Model-View-Controller pattern

    The Model-View-Presenter pattern

    The Model-View-ViewModel pattern

    A MV* pattern comparison

    Summary

    8. Data Binding

    What is data binding?

    Data binding elements

    Data binding directions

    Implementing data binding

    Manual data binding

    Monitoring changes

    Hacking properties

    Defining a binder

    The publish/subscribe pattern

    The observer pattern

    The publisher/subscriber pattern

    Implementing observables

    Using proxies

    The proxy class

    Data binding with proxies

    Summary

    9. Asynchronous Programming and Promises

    Is JavaScript asynchronous?

    Event loop and asynchronous code

    Events, Ajax, and other asynchronous stuff

    Writing asynchronous code

    Using events properties

    Using callbacks

    Callbacks and this

    The callback hell

    Organizing callbacks

    The issues of asynchronous code

    Introducing Promises

    What are Promises?

    The Promise terminology

    Creating Promises

    Consuming Promises

    Catching failures

    Composing Promises

    Using Generators

    Introducing Generators

    Using Generators for asynchronous tasks

    ES7 async/await

    Summary

    10. Organizing Code

    The global scope

    Global definitions

    Creating namespaces

    Namespaces as object literals

    Defining namespaces with IIFE

    The module pattern

    Modules versus namespaces

    Using anonymous closures

    Importing modules

    Augmenting modules

    Loose augmentation

    Overriding a module's methods

    Tight augmentation

    Composing modules

    Submodules

    Module loading

    Modules, scripts, and files

    A simple module loader

    CommonJS modules

    Asynchronous Module Definition

    Merging the module pattern with AMD

    Universal Module Definition

    UMD

    Dependency management

    ECMAScript 6 modules

    ES6 module loading

    Summary

    11. SOLID Principles

    Principle of OOP design

    The Single Responsibility Principle

    The Open/Closed Principle

    The Liskov Substitution Principle

    The Interface Segregation Principle

    The Dependency Inversion Principle

    Dependency inversion, inversion of control, and dependency injection

    Dependency injection approaches

    Summary

    12. Modern Application Architectures

    From scripts to applications

    What is a large-scale application?

    What is an application architecture?

    Goals of an architecture design

    From old-style to Single Page Applications

    Old-style web applications

    Single Page Applications

    The server role

    View composition

    Navigation and routing

    The remote data

    The Zakas/Osmani architecture

    The overall architecture

    The modules

    The Sandbox

    The facade pattern

    The application core

    The mediator pattern

    The base library

    Cross-cutting features and AOP

    The log management example

    Using inheritance

    The Aspect-Oriented Programming approach

    Isomorphic applications

    Summary

    Mastering JavaScript Object-Oriented Programming


    Mastering JavaScript Object-Oriented Programming

    Copyright © 2016 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 author, 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: June 2016

    Production reference: 1220616

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham

    B3 2PB, UK.

    ISBN 978-1-78588-910-3

    www.packtpub.com

    Credits

    About the Author

    Andrea Chiarelli has over 20 years of experience as software engineer and technical writer. Throughout his career, he has used various technologies for the projects he was involved in, ranging from C# to JavaScript, ASP.NET to AngularJS, and REST to PhoneGap/Cordova.

    He has contributed to many online and offline magazines, such as Computer Programming and ASP Today and has coauthored a few books published by Wrox Press.

    Currently, he is a senior software engineer at the Italian office of Apparound Inc., a mobile software company founded in the heart of Silicon Valley, and he is a regular contributor to HTML.it, an Italian online magazine focused on web technologies. You can contact him at https://www.linkedin.com/in/andreachiarelli

    I wish to thank my family for their support, patience and love.

    About the Reviewer

    Lyubomyr Rudko is Senior Software Engineer, and has been developing large web application with JavaScript for the last 6 years. He has great experience in AngularJS, BackboneJS, React.js and Sencha ExtJS. Lyubomyr is a big fan of JavaScript language and truly enjoys sharing his skills and experience with others. Currently, he is working as a Team Technical Lead for Lohika (http://www.lohika.com/elite-teams/). You can contact him at https://ua.linkedin.com/in/lyubomyrrudko.

    www.PacktPub.com

    eBooks, discount offers, and more

    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 [email protected] for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www2.packtpub.com/books/subscription/packtlib

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read 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 a web browser

    Preface

    It is now a fact that JavaScript is the most widely used language in the world. Born as a simple glue between the user and the HTML, it has evolved over the years and has acquired an increasingly important role. Today, its scope is no longer just the Web browser, but it lives also on the server, on the desktop PC, on mobile devices up to embedded devices. JavaScript is no longer a simple language to write some scripts, but a language to create complex applications.

    Unfortunately, many believe that JavaScript cannot compete with programming languages such as C ++, Java or C #. Many developers with a traditional OOP background think that JavaScript does not have the characteristics to be considered a true Object-Oriented language. This book aims to disprove this prejudice and to show that JavaScript has the characteristics to be considered a true OOP language, although with its peculiarities that make it unique. Thanks to the latest innovations introduced by the ECMAScript standard, we will see how we can write robust and efficient code with JavaScript and we can apply those typical principles of Object-Oriented Programming to create scalable and maintainable applications.

    What this book covers

    Chapter 1, A Refresher of Objects, recalls some basic concepts about objects management in JavaScript covering literal objects, constructor functions and classes.

    Chapter 2, Diving into OOP Principles, shows that JavaScript supports all the basic principles that allows us to define it a true OOP language.

    Chapter 3, Working with Encapsulation and Information Hiding, describes some techniques to protect private members of an object, implementing Encapsulation and Information Hiding principles.

    Chapter 4, Inheriting and Creating Mixins, covers the inheritance mechanism of JavaScript based on prototypes and the creation of mixins.

    Chapter 5, Defining Contracts with Duck Typing, focuses on using duck typing instead of relying on type checking and shows some techniques to emulate classical OOP interfaces.

    Chapter 6, Advanced Object Creation, discusses some different ways to create objects and introduces a few Design Patterns such as the Factory Pattern and the Builder Pattern.

    Chapter 7, Presenting Data to the User, explores the most common Presentation Patterns such as Model View Controller Pattern and Model View ViewModel Pattern.

    Chapter 8, Data Binding, explains how to implement Data Binding and describes Patterns such as the Observer Pattern and the Publisher/Subscriber Pattern.

    Chapter 9, Asynchronous Programming and Promises, discusses the issues with asynchronous programming in JavaScript and shows how to overcome them with Promises and other innovative techniques.

    Chapter 10, Organizing Code, analyzes the various approaches to organize JavaScript code in modules: from the classical IIFE to the latest ECMAScript 6 modules.

    Chapter 11, SOLID Principles, explores how to apply the five SOLID Design Principles in order to create scalable and maintainable applications.

    Chapter 12, Modern Application Architectures, describes the most common architectures for JavaScript applications and introduces the Facade and Mediator Patterns.

    What you need for this book

    Most of the code provided in this book is not bound to a specific JavaScript runtime environment, so it could run in any JavaScript environment. However some examples are specific for the Web browser environment, so the console of Web Inspector such as Chrome Developer tools or Firebug is needed.

    Who this book is for

    This book is intended for developers with some knowledge and experience in JavaScript that want to deepen the OOP approach.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Mount the downloaded WebStorm-10*.dmg disk image file as another disk in your system.

    A block of code is set as follows:

    var person = {};

    person.name = John;

    person.surname = Smith;

    person.address = {

                    street: 123 Duncannon Street,

                    city: London,

                    country: United Kingdom

                  };

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    For this book we have outlined the shortcuts for the Mac OX platform if you are using the Windows version you can find the relevant shortcuts on the WebStorm help page  https://www.jetbrains.com/webstorm/help/keyboard-shortcuts-by-category.html.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in 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 at 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.

    Downloading the example code

    You can download the example code files for this book 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 files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-JavaScript-Object-Oriented-Programming. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    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 could 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 to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted 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 [email protected] 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

    If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

    Chapter 1. A Refresher of Objects

    Any JavaScript programmer knows that almost everything in this scripting language is an object—from arrays to functions, from regular expressions to dates. We can say that what is not a primitive data type is an object. But, even the primitive data types such as numbers or strings have object wrappers, that is, they are accessible via objects. So, we can argue that objects are vital in JavaScript, and we need to learn the use of objects as best as we can in order to create better applications. One way, for example, to better use objects is applying the Object-Oriented Programming (OOP) paradigm.

    However, before diving into principles and pattern of this programming approach, let's start this first chapter with a quick recap about objects fundamentals. In particular, the chapter will discuss:

    How to create and manage literal objects

    How to define object constructors

    What a prototype is and how to use it

    The new ECMAScript 2015 class construct and its relation to objects, constructors, and prototypes

    Object literals

    An object is a container of values combined to form a single data structure that has a particular identity. Normally, in fact, an object is used to represent a specific entity such as a person, an order, an invoice, a reservation, and so on, through an aggregation of data and functionalities.

    The data is called properties and are represented by pairs of names and values. The functionalities are usually called methods and are represented by functions, even if they are nothing more than the same pairs of names and values as for properties, where values happen to be functions.

    The simplest way to create an object in JavaScript is the literal representation, as shown in the following example:

    var emptyObject = {};

    var person = {name: John, surname: Smith};

    Through the literal notation, we represent an object by enclosing its properties and methods in braces. In the first statement, we created an empty object, an object without properties nor methods; all in all, not very useful but important to understand that an object is basically a list of pairs of values and, as with every list, it can be empty.

    In the second declaration, in order to define the object person, we listed two pairs of strings separated by commas. Each pair consists of two strings separated by a colon. The first string is the name of the property while the second one represents its value.

    Properties

    To assign a name to the properties of an object, we don't have the same restrictions as for the JavaScript variable names. We can use any string, even if there is some constraint when accessing properties with particular names, as we are going to see.

    The double or single quotes around the property name are generally optional, but they are required when the name does not follow the rules for variable names. So, we could write our definition of person as follows:

    var person = {name: John, surname: Smith};

    But if we want a definition like the following, we are forced to use double or single quotes:

    var person = {first-name: John, second-name: Smith};

    We can assign any value to an object property and any JavaScript expression, including another object. So, we can create nested objects as shown here:

    var person = {name: John,

                  surname: Smith,

                  address: {

                    street: 13 Duncannon Street,

                    city: London,

                    country: United Kingdom

                  }};

    As we can see, an object with its specific properties is assigned to the address property.

    To access the values stored in an object property, we have two approaches. The first approach is the so-called dot-notation, by which we indicate an object and the property we're interested in, separated by a point:

    var name = person.name;

    This is usually the most used approach because it is more compact and quite familiar to developers who have worked with other programming languages.

    Using the second approach, we specify the properties of an object by indicating its name as a string in square brackets:

    var name = person[name];

    This approach is mandatory when the property name does not follow the rules for JavaScript's variable names. For example, we cannot use the dot-notation to access a property named first-name.

    If we try to access a non-existing property of an object, an error is not generated but returns the undefined value. In the following example, therefore, the age variable will get the undefined value:

    var age = person.age;

    If we try to assign a value to a not yet defined property, we actually create this property initializing it with the assigned value:

    person.age = 28;

    This example shows us the dynamic nature of JavaScript objects. The object's structure is very flexible and can be changed dynamically during the execution of a script. This feature gives us an alternative way for the creation of an object based on a kind of incremental definition. In practice, instead of completely defining a literal representation of our object, we can start from a basic representation and gradually enrich it with the properties we want. Following this approach, we can define our object person as follows:

    var person = {};

    person.name = John;

    person.surname = Smith;

    person.address = {

                      street: 123 Duncannon Street,

                      city: London,

                      country: United Kingdom

                    };

    person.age = 28;

    Besides being able

    Enjoying the preview?
    Page 1 of 1