Inheritance in JavaScript: Prototypal Approach
JavaScript uses a prototype-based inheritance model, often referred to as "prototypal inheritance" or "behavior delegation." Unlike classical inheritance in languages like Java or C++, JavaScript’s approach involves prototypes and prototype chains.
Person Class
This defines a Person function that acts as a constructor. It sets default values for FirstName
and LastName
. The getFullName
method is added to the Person.prototype
object, making it available to all instances of Person
.
Example Code
function Person(firstName, lastName) {
this.FirstName = firstName || "unknown";
this.LastName = lastName || "unknown";
}
Person.prototype.getFullName = function() {
return this.FirstName + " " + this.LastName;
}
Student Class
This defines a Student constructor that inherits from Person. The Person.call(this, firstName, lastName)
ensures the Person constructor is called first, setting up the FirstName
and LastName
properties. The Student constructor adds its own properties (SchoolName
and Grade
).
Example Code
// Two ways to set up inheritance:
// Option 1 (less common):
// Student.prototype = Person.prototype;
// Option 2 (recommended):
Student.prototype = new Person();
Student.prototype.constructor = Student;
function Student(firstName, lastName, schoolName, grade) {
Person.call(this, firstName, lastName);
this.SchoolName = schoolName || "unknown";
this.Grade = grade || 0;
}
var std = new Student("James", "Bond", "XYZ", 10);
Output
James Bond
Key Points
- In JavaScript, inheritance happens through the prototype chain.
- Objects inherit properties and methods from their prototype.
- The
constructor
property identifies the constructor function that created the object. - Option 2 for setting up inheritance (creating a new object with
new Person()
) is generally preferred.
Additional Considerations
- JavaScript also supports class-based inheritance (introduced in ES6) for a more familiar syntax.
- Inheritance can lead to complex prototype chains. Be mindful of potential issues like prototype pollution.
By understanding prototypal inheritance, you can effectively implement inheritance-like functionality in JavaScript.