Search⌘ K
AI Features

Using Object Prototypes

Explore how JavaScript object prototypes work to share methods and properties among instances efficiently. Understand the link between constructor functions and their prototypes, how to override properties, check ownership, and extend built-in objects. This lesson prepares you for mastering object inheritance concepts in advanced JavaScript programming.

Prototypes may provide a great solution for both the resource wasting and poor maintainability issues. As you learned in the previous Chapter (A Quick Overview of Function Prototypes), functions in JavaScript are created with a prototype property, which is an object containing properties and methods that should be available to instances of a particular object type.

Modifying the Employee construction as shown in the Listing below offers a remedy for the issues mentioned earlier.

Listing: Construction with prototype

<!DOCTYPE html>
<html>
<head>
  <title>Construction with prototype</title>
  <script>
    var Employee = function (id, firstName,
      lastName, title) {
      this.id = id;
      this.firstName = firstName;
      this.lastName = lastName;
      this.title = title;
    }

    Employee.prototype.getFullName =
      function () {
        return this.lastName + ", " + this.firstName;
      }

    var philip = new Employee(1, "Philip", "Moore",
      "CEO");
    var jane = new Employee(2, "Jane", "Mortimer",
      "CFO");

    console.log(philip.getFullName());
    console.log(jane.getFullName());
  </script>
</head>
<body>
  Listing 8-16: View the console output
</body>
</html>

To understand how prototypes work, here is a short explanation. Each function has a prototype property; whenever a function is created, its prototype property is also set. By default, all prototypes get a property called constructor that points to the function used to create the object ...