Classic JavaScript inheritance mode

Keywords: Javascript

Understanding JavaScript inheritance is helpful for normal development. Here are four classic inheritance patterns.

1. Prototype chain
Disadvantages: it belongs to the traditional inheritance mode and inherits both the constructor and the prototype

Father.prototype.lastName = "king";
function Father (sex) {
	this.sex = sex
}
function Son () {}
var father = new Father("male");
Son.prototype = father;
var son = new Son();
console.log(son.lastName) // king
console.log(son.sex) // male

2. Borrow constructor
Disadvantage: cannot inherit the prototype of borrowed constructor

function Father (lastName) {
	this.lastName = lastName
}

function Son (lastName) {
	Person1.Father(this, lastName)
}

var son = new Son("king")
console.log(son.lastName) // king
Father.prototype.lastName = "Zhao"
console.log(son.lastName) // king

3. Sharing prototype
Disadvantage: as long as one object prototype changes, other objects will be affected

Father.prototype.lastName = "king";
function Father () {}
function Son () {}
Son.prototype = Father.prototype;
var son = new Son();
var father = new Father();
console.log(son.lastName); // king
console.log(father.lastName); // king
son.prototype.lastName = "Zhao";
console.log(son.lastName); // Zhao
console.log(father.lastName); // Zhao

4. Holy Grail mode
Advantage: it is beneficial to inherit the prototype and properties of the parent object, while when the prototype of the child object changes, the parent object is not affected by it

function inherit (Target, Origin) {  // Target inherits Origin
	function F () {}; // Intermediate constructor
	F.prototype = Origin.prototype; 
	Target.prototype = new F(); // Make Target inherit from instance object of F, so that Target and Origin do not interfere with each other
	Target.prototype.constuctor = Target;
}

function Father () {};
function Son () {};
inherit(Son, Father)

var son = new Son();
var father = new Father();
Father.prototype.lastName = "king";
console.log(son.lastName) // king
console.log(father.lastName) // king

son.lastName = "Zhao";
console.log(son.lastName) // Zhao
console.log(father.lastName) // king

If you have any questions, welcome to point out, grow together, ha ha.

Posted by jebadoa on Fri, 24 Jan 2020 07:12:53 -0800