This is the most optimized pattern. It uses a borrowed constructor for instance properties and a parasitic approach (Object.create) to inherit the prototype without executing the supertype constructor twice.
Pros:
Supertype is only called once, avoiding unnecessary properties on the prototype.- Maintains the prototype chain, allowing
instanceof and isPrototypeOf() to work correctly.
function inheritPrototype(subType, superType){
// Create a copy of the supertype prototype
var prototype = Object.create(superType.prototype)
// Restore the constructor property
prototype.constructor = subType
// Assign the new prototype to the subtype
subType.prototype = prototype
}
function Supertype(name) {
this.name = name
this.colors = ['white', 'black']
}
Supertype.prototype.getName = function() {
console.log('name', this.name)
}
function Subtype(name) {
Supertype.call(this, name)
}
inheritPrototype(Subtype, Supertype);
Subtype.prototype.sayName = function(){
console.log('sayName', this.name)
}
const instance1 = new Subtype('奔驰 S')
instance1.colors.push('blue')
const instance2 = new Subtype('奔驰 G')