To implement inheritance, you must provide a parent class (which class to inherit from, and which properties to inherit from)
function Person(name) {
this.name = name
this.sum = function(){
alert(this.name)
}
}
Person.prototype.age = 10
Copy the code
1. Prototype chain inheritance
function parent(){
this.name = 'joe'
}
parent.prototype = new Person()
var son = new parent()
Copy the code
Features: The instance inherits all constructor properties, superclass constructor properties, and superclass prototype properties
Disadvantages: will inherit all attributes of the parent class, can not pass parameters to the parent class attribute, inheritance is single
Constructor inheritance
function Con() {
Person.call(this.'honghong')
this.age = 12
}
var con1 = new Con()
Copy the code
Features:
1. Only the attributes of the parent constructor are inherited
2. A subinstance can pass parameters to its parent instance
3. The shortcomings of prototype chain inheritance are solved
4. Multiple inheritance can be realized by calling multiple constructors
Disadvantages:
1. Only the attributes of the parent constructor are inherited, and no parent prototype is inherited
2. Each new instance has a bloated copy of the parent constructor
3. Composite inheritance (composite prototype chain inheritance and borrowed constructor inheritance)
function SubType(name){
Person.call(this, name) // Constructor inheritance
}
SubType.prototype = new Person() // Prototype chain inheritance
var sub = new SubType('mom')
console.log(sub.name) // 'mom'
console.log(sub.age) / / '10'
Copy the code
Features:
1. Combined with the advantages of the two modes, can inherit the prototype of the parent class, parameter transfer and reuse
2. Constructor properties introduced by each new instance are private
Disadvantages:
If the parent constructor is called twice (which costs memory), the subclass constructor replaces the parent constructor on the prototype
Parasitic combinatorial inheritance
function content(obj) {
function F(){}
F.prototype = obj // The parent class is inherited here
return new F()
}
var con = content(Person.protype)
function Sub(name){
Person.call(this, name) // Inherits the attributes of the parent constructor
}
Sub.prototype = con // Inherits the con instance
con.constractor = Sub // Remember to fix the constructor
var sub = new Sub('goodJob')
console.log(sub.age, sub.name) // 10, 'goodJob'
Copy the code