Differential inheritance links a derived object to a generic parent, then specializes it by adding or overriding properties. Each object borrows the parent’s shape while defining its differences. section 1.2 section 2.1.2
JavaScript’s internal [[Prototype]] reference creates the link. Property resolution starts at the calling object and travels upward, so local properties such as enroll are found immediately while inherited methods such as getAddress are resolved through the prototype chain. section 1.2 section 2.1.2
Use the link-versus-copy distinction to compare inheritance approaches:
- Differential inheritance preserves references between derived and parent objects; class-based inheritance copies state and behavior from classes. section 2.1.2
- Object composition can produce a similar public shape by copying properties from Person and Student into a new object, without prototype inheritance. section 1.2
- Long prototype graphs share changes broadly: modifying a base object can affect derived objects at runtime, a risk identified as prototype pollution. section 1.2
Extending transaction objects
Create hashTransaction with transaction as its prototype, then add calculateHash. Create moneyTransaction with hashTransaction as its prototype, add funds and addFunds, and reuse calculateHash together with sender and recipient. section 2.1.2
Inspect the Student-to-Person prototype hierarchy and follow how inherited properties are reached. section 1.2
Listing 2.4 Creating hashTransaction with basic hashing calculation
const hashTransaction = Object.create(transaction);
hashTransaction.calculateHash = function calculateHash() { #1
const data = [this.sender, this.recipient].join(''); #2
let hash = 0, i = 0;
while (i < data.length) {
hash = ((hash << 5) - hash + data.charCodeAt(i++)) << 0;
}
return hash**2; #3
}
hashTransaction.calculateHash(); // 237572532174000400
Inspect a concrete Object.create example that adds calculateHash to a linked transaction object. section 2.1.2
