Prototype chain inheritance
function Show(){
this.name="run";
}
function Run(){
this.age="20"; //Run inherits Show from the prototype to form a chain
}
Run.prototype=new Show();
var show=new Run();
alert(show.name)// Result: run
Copy the code
Constructor inheritance (object impersonation inheritance) To solve the problems of shared references and the inability of supertypes to pass arguments, we use a technique called borrowed constructors, or object impersonation (forged objects, classical inheritance) to solve both problems
function Box(age){
this.name=['Lee'.'Jack'.'Hello']
this.age=age;
}
function Desk(age){
Box.call(this,age); // Object impersonation, passing parameters to the supertype
}
var desk = new Desk(200);
alert(desk.age);/ / 200
alert(desk.name);//['Lee','Jack','Hello']
desk.name.push('AAA'); // Add new data to desk only
alert(desk.name)//['Lee','Jack','Hello','AAA']
Copy the code
3. Composite inheritance (stereotype chain inheritance + constructor inheritance) borrowing constructors solves both problems, but without stereotypes, reuse is impossible. Therefore, we need the pattern of stereotype chain + borrowing constructor, which is called combinatorial inheritance.
function Box(age) {
this.name = ['Lee'.'Jack'.'Hello']
this.age = age;
}
Box.prototype.run = function () {
return this.name + this.age;
};
function Desk(age) {
Box.call(this, age); // Object impersonation
}
Desk.prototype = new Box(); // Prototype chain inheritance
var desk = new Desk(100);
alert(desk.run());
Copy the code
Four. Primitive inheritance is inheritance that leverages stereotypes and creates new objects based on existing objects without having to create custom types
function obj(o) { // Pass a literal function
function F() {} // Create a constructor
F.prototype = o; // Assign the literal function to the constructor's prototype
return new F(); // Finally returns the instantiated constructor
}
var box = { // A literal object
name : 'Lee'.arr : ['brother'.'sister'.'sister']};var box1 = obj(box); / / pass
alert(box1.name);
box1.name = 'Jack';
alert(box1.name);
alert(box1.arr);
box1.arr.push('parents');
alert(box1.arr);
var box2 = obj(box); / / pass
alert(box2.name);
alert(box2.arr); // The reference type is shared
Copy the code
Five. Parasitic combinatorial inheritance Parasitic combinatorial inheritance solves the problem of two invocations, and combinatorial inheritance has two invocations
The basic model is as follows:
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
function inheritPrototype(subType, superType) {
var prototype = object(superType.prototype); // Create an object
prototype.constructor = subType; // Enhance objects
subType.prototype = prototype; // Specify the object
}
Copy the code