Mastering JavaScript Object-Oriented Programming

4.4 (5 reviews total)
By Andrea Chiarelli
  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies
  1. A Refresher of Objects

About this book

ECMAScript 6 introduces several new Object-Oriented features that drastically change the way developers structure their projects. Web developers now have some advanced OOP functionality at their disposal to build large-scale applications in JavaScript.

With this book, we'll provide you with a comprehensive overview of OOP principles in JavaScript and how they can be implemented to build sophisticated web applications. Kicking off with a subtle refresher on objects, we'll show you how easy it is to define objects with the new ES6 classes. From there, we'll fly you through some essential OOP principles, forming a base for you to get hands-on with encapsulation.

You'll get to work with the different methods of inheritance and we'll show you how to avoid using inheritance with Duck Typing. From there, we'll move on to some advanced patterns for object creation and you'll get a strong idea of how to use interesting patterns to present data to users and to bind data. We'll use the famous promises to work with asynchronous processes and will give you some tips on how to organize your code effectively.

You'll find out how to create robust code using SOLID principles and finally, we'll show you how to clearly define the goals of your application architecture to get better, smarter, and more effective coding. This book is your one-way ticket to becoming a JavaScript Jedi who can be counted on to deliver flexible and maintainable code.

Publication date:
June 2016
Publisher
Packt
Pages
292
ISBN
9781785889103

 

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 to dynamically create the properties of an object, we can also destroy them at runtime using the delete statement. The following example shows how to remove the address property from our person object:

delete person.address; 

After the removal of the address property, any attempt to access it will return the value undefined.

Methods

While object properties represent data, methods represent actions that an object can perform. From a syntactical point of view, the definition of an object's method is quite similar to the definition of a property. Here's an example:

function showFullName() { 
  return "John Smith"; 
} 
 
person.fullName = showFullName; 

We can also assign a method to an object inside its literal representation as shown here:

var person = {name: "John", 
        surname: "Smith", 
        showFullName: function() { 
          return "John Smith"; 
        } 
}; 

ECMAScript 2015 allows us to define methods in literal notation in a more direct form, as in the following example:

var person = {name: "John", 
        surname: "Smith", 
        showFullName() { 
          return "John Smith"; 
        } 
}; 

Actually, the distinction between properties and methods is somewhat artificial in JavaScript. In fact, since the functions are also objects, a method is nothing more than a property that has been assigned a function.

Incidentally, since the value assigned to a property can change at runtime, it is possible that a property, which was initially assigned a function, can then be assigned a different value, such as a string or a number. Unlike other programming languages, a method is not a stable condition for a member of an object, it is not a characteristic of a specific property. We can simply affirm that a property is a method when it has a function assigned, but it is a dynamic condition.

In the previous example, we defined a function that simply returns a string and we assigned that function name to a new property of the person object. Note that we are not assigning the result of the function call to the property, but the function itself by means of its name.

The fullName property, since it has been assigned a function, is actually a method. To run it, we must refer to it by specifying parentheses as in a usual function call:

var nameAndSurname = person.fullName(); 

Of course, we can assign an anonymous function to a property directly as in the following example:

person.fullname = function () { 
  return "John Smith"; 
} 

The method that we just defined in the example is not so useful. It always displays the same string even if we assign a different value to name and surname of the person object. It would be useful to have a way to display the current value of the corresponding properties.

JavaScript allows us to reach this goal through the this keyword. The keyword represents the object when the method is invoked. So, we can rewrite our method in the following way:

person.fullName = function () { 
  return this.name + " " + this.surname; 
}; 

This guarantees the correct display of the current data at the time of the call.

 

Object constructors


The creation of an object, as we have seen in the examples, is quite straightforward using the literal notation. We do not have to define a class, but we directly create the object just when we need it, and hopefully we can change its structure during the execution of our script.

Suppose, we need multiple objects of the same type, for example more person objects, which share the same structure.

Using the literal notation, we will have to repeat the definition for each object that we want to create, which is essential to identify the single person but unnecessarily repetitive for constant members such as the methods. In other words, using the literal notation in the definition of the objects, we get a non reusable result. For example, if we want to create two person objects, we need to write the following code:

var johnSmith = {name: "John", 
                  surname: "Smith", 
                  address: { 
                    street: "13 Duncannon Street", 
                    city: "London", 
                    country: "United Kingdom" 
                  }, 
                  displayFullName = function() { 
                    return this.name + " " + this.surname; 
                  } 
                }; 
var marioRossi = {name: "Mario", 
                   surname: "Rossi", 
                   address: { 
                     street: "Piazza Colonna 370", 
                     city: "Roma", 
                     country: "Italy" 
                   }, 
                   displayFullName = function() { 
                     return this.name + " " + this.surname; 
                   } 
                 }; 

Therefore, in order to avoid defining from scratch objects that have the same structure, we can use a constructor—a JavaScript function invoked using the new operator. Let's see how to create a constructor for the person object with an example:

function Person() { 
  this.name = ""; 
  this.surname = ""; 
  this.address = ""; 
  this.email = ""; 
 
  this.displayFullName = function() {...}; 
 
} 

This function defines the properties of our object by assigning them to the this keyword and setting default values. Even if this constructor may seem useless since it assigns just empty strings to the properties, it defines a common structure to any object created by it. So, in order to create an object of type person, we will have to call the function by prefixing the new operator:

var johnSmith = new Person(); 
johnSmith.name = "John"; 
johnSmith.surname = "Smith"; 
 
var marioRossi = new Person(); 
marioRossi.name = "Mario"; 
marioRossi.surname = "Rossi"; 

In this way, when we want to create multiple objects with the same structure, we will limit ourselves to just set the specific values that distinguish one object from another.

As you can see, the name given to the constructor is capitalized. This is not a requirement for JavaScript, but a common convention that helps to distinguish regular functions from constructors.

In the definition of a constructor, we can expect the presence of parameters that can be used in the initialization of our object. For example, consider the following definition of the constructor of the person object:

function Person(name, surname) { 
  this.name = name; 
  this.surname = surname; 
  this.address = ""; 
  this.email = ""; 
  this.displayFullName = function() {...}; 
} 

It allows us to create and initialize an object by specifying values directly in the constructor call, as in the following example:

var johnSmith = new Persona("John", "Smith"); 
var marioRossi = new Persona("Mario", "Rossi"); 

It is very important to use the new operator while creating an object through a constructor. In fact, if we forget it, what we get is not the creation of an object, but the execution of the function, with unpredictable results. For example, suppose that we try to create a person object omitting the new operator:

var johnSmith = Person(); 

The value of the variable johnSmith will be undefined, since the function Person() returns no value. In addition, all the properties and methods defined within the body of the function will be assigned to the object represented by this keyword in the execution context of the function, as can be for example the global object window in a browser. This assignment could redefine the value of variables with the same name causing side effects that are difficult to predict and to debug.

We can reduce the risk of such oversights by resorting to the use of strict mode:

function Person() { 
  "use strict"; 
  ... 
} 

In strict mode, the value of the object represented by the this keyword is undefined during the execution of the function. This generates a runtime error while trying to access the property of an object that does not exist, thus avoiding unwanted invocations of the constructor.

Unfortunately, this approach is not sufficient when the constructor is defined inside a namespace:

var mankind = { 
  ... 
  Person: function(name, surname) { 
    'use strict'; 
    this.name = name; 
    this.surname = surname; 
    ... 
  } 
}; 
 
var johnSmith = mankind.Person("John", "Smith"); 

In this case, the this keyword represents the mankind object, so we will not have a runtime error that warns us of the incorrect use of the constructor, but the properties name and surname will be attached to the mankind object.

The Object() constructor

We have seen how the use of a constructor offers us a higher level of abstraction in the creation of objects. In this section, we explore a particular constructor provided to us by JavaScript—the Object() constructor.

This constructor allows us to create a generic object, as shown in the following example:

var person = new Object(); 
person.name = "John"; 
person.surname = "Smith"; 

Here, we use the new operator to create a new instance of an empty object and then we create properties by assigning values, as in the literal approach.

Actually, creating an object using the literal notation or creating it by means of the Object() constructor is the same thing. Every object created using the literal notation has Object() as its implicit constructor. We can realize it by accessing the constructor property that every object has the following:

var person = {}; 
console.log(person.constructor == Object);  //result: true 

The Object() constructor is also able to generate object instances from any JavaScript expression, as shown by the following code:

var number = new Object(12); 
var anotherNumber = new Object(3*2); 
var string = new Object("test"); 
var person = new Object({name: "John", surname: "Smith"}); 

Apart from the last statement, which is equivalent to the creation of an object via its literal representation, the first three statements create an object from a primitive data type, such as a number or string. The result is not just a numerical value or a string value, but built-in objects specialized in handling numeric values and strings.

We will return later in the book on the Object() constructor for use in advanced mode.

 

Object prototypes


The flexibility of JavaScript objects is expressed primarily through the possibility of changing their structure even after their creation. Even while using a constructor to create an object, we continue to have this possibility. For example, you can write the following code:

var johnSmith = new Person("John", "Smith"); 
var marioRossi = new Person("Mario", "Rossi"); 
 
johnSmith.greets = function() { 
  console.log("Hello " + this.name + " " + this.surname + "!"); 
}; 

This code will create a new method greets() for the johnSmith object without affecting the structure of marioRossi.

Basically, while creating objects, we can start from a common structure defined by a constructor and then customize it to our needs.

But how do we change the structure of all objects created using a constructor? For example, suppose that after creating several object using the Person() constructor, we want all the Person instances to have the greets() method. We can do it by exploiting one of the most interesting features of Object-Oriented Programming in JavaScript—the prototype.

In our case, we will proceed in the following way:

Person.prototype.greets = function() { 
  console.log("Hello " + this.name + " " + this.surname + "!"); 
}; 

This assignment means that all objects created using the Person() constructor will instantly have available also the greets() method.

To be precise, the new method is not directly attached to each object, but it is accessible as if it were its method. This is possible, thanks to the prototyping mechanism that represents the basis of inheritance in Object-Oriented Programming in JavaScript, as we will discuss later in the book.

In JavaScript, the prototype of an object is a kind of reference to another object. The objects we create through the literal notation implicitly refer to Object as their prototype.

When we create an object using a constructor, its prototype object is the prototype of the constructor.

If we try to access a property or method of an object that the object itself has not, JavaScript looks for it among the properties and methods of its prototype. So, in our previous example, if we try to access the greets() method of the marioRossi object, JavaScript does not find it among its methods, but it will find it among the methods of its prototype.

The prototype of an object can in turn have another prototype. In this case, the search for a property or method goes up the prototype chain until you get object-the basic prototype of all objects.

JavaScript built-in objects have a prototype reference too. In most cases, their management is quite similar to the prototypes management of objects created through our constructors. This allows us to extend functionality not provided by the built-in objects in a rather simple and elegant way.

For example, if we want to make a padding method available to all strings, we can work on the prototype of the String() constructor, as shown here:

String.prototype.padLeft = function(width, char) { 
  var result = this; 
  char = char || " "; 
 
  if (this.length < width)  { 
    result = new Array(width - this.length + 1).join(char) + this; 
  } 
  return result; 
}; 

With this definition we can use padLeft() as if it were a built-in method of all strings, as shown in the following example:

console.log("abc".padLeft(10, "x"));      //"xxxxxxxabc" 
 

Using classes


So far, we created objects using two mechanisms: the literal notation and the constructor. These mechanisms let us create objects with a simple approach, without too many formalities.

However, most developers are used to creating objects from the class construct. In fact, many Object-Oriented languages let the developer define classes and create objects as an instance of those classes.

The ECMAScript 2015 (also known as ECMAScript 6 or ES6) specifications introduce the class construct in JavaScript too. However, this construct has nothing to do with the classes of the traditional Object-Oriented Programming paradigm.

While in other languages, such as Java or C#, a class is an abstract description of the structure of an object, in JavaScript the class construct is just a syntactic simplification of the approaches to create objects we have already seen. The JavaScript class construct provides a much simpler and clearer syntax for managing constructors, prototypes, and inheritance.

The new class construct creates order among the different ways of object creation and aims to apply the best practice in prototype management.

Let's take a look at what a class looks like:

class Person { 
  constructor(name, surname) { 
    this.name = name; 
    this.surname = surname; 
  } 
} 

This class defines a constructor for objects of type Person. It is fully equivalent to the following old-style JavaScript code:

function Person(name, surname) { 
  "use strict"; 
  this.name = name; 
  this.surname = surname; 
} 

We can realize that classes are just syntactic sugar for the constructor's definition, simply getting the type of a class by means of the typeof statement:

console.log(typeof Person);   //function 

We can create an object using a class just as we do with constructors, as shown by the following example:

var person = new Person("John", "Smith"); 

However, unlike a constructor, we cannot invoke a class like a function, since the following code will raise an exception:

var person = Person("John", "Smith"); 

This ensures that we do not run the risk of the side effects that affect traditional constructors.

We can assign a class definition to a variable and then use the variable as an object constructor, as in the following example:

var Person = class { 
  constructor(name, surname) { 
    this.name = name; 
    this.surname = surname; 
  } 
}; 
 
var person = new Person("John", "Smith"); 

From a syntactic point of view, a class is a collection of methods included in braces and identified by a name.

One of these methods is the constructor() method, whose task is to define and initialize the properties:

class myClass { 
  constructor(value1, value2) { 
    this.property1 = value1; 
    this.property2 = value2; 
    this.property3 = ""; 
  } 
 
  method1() { 
    ... 
  } 
 
  method2() { 
    ... 
  } 
} 

The constructor of a class is a method with the reserved name constructor. You cannot have more than one constructor() method in a class.

The constructor method returns, by default, the new instance if it has no return statement, as a common JavaScript constructor. However, it is possible to override the default behavior by inserting a return statement in the constructor body. For example, the following code defines a constructor that returns a literal instance:

class myClass { 
  constructor(value) { 
    return { property1: value, property2: "" }; 
  } 
} 
 
var x = new myClass("foo"); 

All the methods defined in a class are attached to the prototype property of the class. The prototype property of a class is the prototype that the objects created using this class will have.

The choice to attach methods to the prototype of the class is the result of the application of a common best practice. Since usually methods are not dynamically changed, by attaching them to the prototype, this helps us to optimize memory management. In fact, if methods are not attached to the prototype, then they should be replicated on each newly created object with a proportional need of memory. Attaching methods to the prototype ensures that we have just one copy of them for all objects created from that class.

Unlike functions, classes are not hoisted. This means that while a function can be used before its declaration, a class cannot.

So, the following code will raise an exception:

var person = new Person(); 
 
class Person {...} 

The features of classes described so far are the basic ones. We will come back to explore other features of new class construct later in the book.

 

Summary


In this introductory chapter, we recalled some concepts related to object management in JavaScript.

We explored two approaches in creating objects: the literal-based approach and the constructor-based one. The first one is very simple but not practical when we need more generalization, while the second approach is a bit more complex but effective.

We also introduced the new class construct and analyzed how it simplifies the definition of object constructors and the use of prototypes.

In the next chapter, we will analyze how JavaScript applies the Object-Oriented Programming principles.

About the Author

  • Andrea Chiarelli

    Andrea Chiarelli has over 20 years experience as a software engineer and technical writer. In his professional career, he has used various technologies for the projects he has been involved in: from C# to JavaScript, from Angular to React, from ASP.NET to PhoneGap/Cordova. He has contributed to many online and offline magazines and has been the author of a few books published by Wrox Press and Packt. Currently, he is a senior software engineer at the Italian office of Apparound, Inc. and a regular contributor to HTML.it, an Italian online magazine focused on web technologies. You can follow him on Twitter at @andychiare.

    Browse publications by this author

Latest Reviews

(5 reviews total)
Purchase process is convenient
this is a good book, ES6 is just added to the end of each chapters
I must say I haven't finished it yet, but so far the book is very clear.
Book Title
Access this book, plus 7,500 other titles for FREE
Access now