JavaScript Object Prototypes
All JavaScript objects inherit properties and methods from a prototype.
In the previous chapter, we learned how to use an object constructor:
Example:
function Employee(first, last, age, department) { this.firstName = first; this.lastName = last; this.age = age; this.department = department; } const manager = new Employee("Alice", "Johnson", 35, "HR"); const engineer = new Employee("Bob", "Smith", 30, "Engineering");
We also learned that you cannot add a new property to an existing object constructor directly:
Example:
To add a new property to a constructor, you must add it to the constructor function:
Example:
function Employee(first, last, age, department) { this.firstName = first; this.lastName = last; this.age = age; this.department = department; this.country = "USA"; }
Prototype Inheritance
All JavaScript objects inherit properties and methods from a prototype:
- Date objects inherit from Date.prototype
- Array objects inherit from Array.prototype
- Employee objects inherit from Employee.prototype
The Object.prototype is at the top of the prototype inheritance chain. Date objects, Array objects, and Employee objects all inherit from Object.prototype.
Adding Properties and Methods to Objects
Sometimes you want to add new properties or methods to all existing objects of a given type. You can do this using the prototype property.
Using the Prototype Property
The JavaScript prototype property allows you to add new properties to object constructors:
Example:
function Employee(first, last, age, department) { this.firstName = first; this.lastName = last; this.age = age; this.department = department; } Employee.prototype.country = "USA";
The JavaScript prototype property also allows you to add new methods to object constructors:
Example:
function Employee(first, last, age, department) { this.firstName = first; this.lastName = last; this.age = age; this.department = department; } Employee.prototype.getFullName = function() { return this.firstName + " " + this.lastName; };