1. Prototype chain inheritance
function Parent () {
this.name = 'kevin';
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child () {
}
Child.prototype = new Parent();
var child1 = new Child();
console.log(child1.getName()) // kevin
Copy the code
Question:
1. Attributes of the reference type are shared by all instances. 2
2. Borrow constructors (classical inheritance)
function Parent (name) {
this.name = name;
}
function Child (name) {
Parent.call(this, name);
}
var child1 = new Child('kevin');
console.log(child1.name); // kevin
var child2 = new Child('daisy');
console.log(child2.name); // daisy
Copy the code
Disadvantages: Methods are defined in constructors and are created each time an instance is created.
3. Combinatorial inheritance
function Parent (name) {
this.name = name;
this.colors = ['red'.'blue'.'green'];
}
Parent.prototype.getName = function () {
console.log(this.name)
}
function Child (name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
var child1 = new Child('kevin'.'18');
child1.colors.push('black');
console.log(child1.name); // kevin
console.log(child1.age); / / 18
console.log(child1.colors); // ["red", "blue", "green", "black"]
var child2 = new Child('daisy'.'20');
console.log(child2.name); // daisy
console.log(child2.age); / / 20
console.log(child2.colors); // ["red", "blue", "green"]
Copy the code
4. Original type inheritance
function createObj(o) {
function F(){}
F.prototype = o;
return new F();
}
Copy the code
Parasitic inheritance
function createObj (o) {
var clone = object.create(o);
clone.sayName = function () {
console.log('hi');
}
return clone;
}
Copy the code
Parasitic combinatorial inheritance
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
function prototype(child, parent) {
var prototype = object(parent.prototype);
prototype.constructor = child;
child.prototype = prototype;
}
// When we use:
prototype(Child, Parent);
Copy the code