Using Object Prototypes
In this lesson, we get acquainted with object prototypes and their usage in JavaScript. Let's begin!
We'll cover the following...
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 instance. As shown at the right side of Figure 8-3, the Employee.prototype has a ...