User Constructor in JavaScript

The User constructor is a JavaScript function designed to model a user within a fitness application. This constructor function is responsible for storing a user's name and their exercise sessions. It also provides methods for adding new sessions and retrieving user data, making it a comprehensive model for managing user information.

Overview

When you create a JavaScript object using the User constructor, you are essentially creating a user model. This model is not just a simple data structure; it includes private variables and public methods for managing the data. The User constructor encapsulates the user's name and exercise sessions, providing a structured way to interact with this data.

User Model

The user model created by the User constructor function is depicted in Figure 14.2. This figure illustrates how the model is structured, highlighting the integration of both data and methods within the object.

Figure 14.2. A user model created by the User constructor function Figure 14.2. A user model created by the User constructor function

The User Constructor

The User constructor is detailed in Listing 14.1. This listing provides the code for the constructor, showcasing how it is implemented in JavaScript.

Listing 14.1. The User constructor (http://jsbin.com/suzala/edit?js,console) Listing 14.1. The User constructor (http://jsbin.com/suzala/edit?js,console)

Key Features

  • Name Parameter: The constructor includes a name parameter to store the user's name.
  • Private Variables: Some variables are declared using var to keep them private within the constructor.
  • Public Methods: Two public methods, addSession and getData, are assigned to the this object.
    • addSession: This method allows the addition of new exercise sessions.
    • getData: This method retrieves user data, including a copy of the sessions array and a total property that holds the total duration of the logged sessions.

The getData method uses the slice method with no arguments to create a copy of the sessions array. This approach prevents users from modifying the sessions array outside the addSession method, ensuring data integrity.

Example Usage

Here is an example of how the User constructor can be used:

var user = new User("Mahesha");
user.addSession("2017-02-05", 120);
user.addSession("2017-02-06", 35);
console.log(user.getData().total); // Outputs: 155

In this example, a new user named "Mahesha" is created. Two exercise sessions are added, and the total duration of these sessions is retrieved using the getData method.

FAQ (Frequently asked questions)

What does the User constructor store?

What methods does the User constructor include?

What does Listing 14.1 show?