Comparative Analysis of Common Inheritance Patterns in JavaScript
1. Prototype Chianing Inheritance (Simplest Approach)
function Parent(name) {
this.name = name;
this.favoriteSports = ['basketball', 'football'];
this.location = { country: 'China', city: 'Jiangsu' };
}
function Child(name) {
this.greet = function() { console.log('I am a child'); };
}
Child.prototype = new Parent(); // Core mechanism
const john = new Child('john');
console.log(john.favoriteSports); // ['basketball', 'football']
Pros:
- Straightforward and easy to grasp
- Minimal setup required
Cons:
- Cannot pass arguments to the parent constructor during child instantiation
- Shared references for objects and arrays across all instances — modifying one affects others:
const alice = new Child('alice');
alice.favoriteSports.push('tennis');
alice.location.district = 'Jianye District';
console.log(john.favoriteSports); // ['basketball', 'football', 'tennis']
console.log(john.location.district); // 'Jianye District'