1. 原型链继承
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())
缺点:
- 引用类型的属性被所有实例共享
- 在创建Child实例时,不能向Parent传参
2.借用构造函数继承(经典继承)
function Parent(name) {
this.name = name;
}
function Child (name) {
Parent.call(this, name)
}
var child1 = new Child('kevin');
console.log(child1.name)
优点:
- 避免了引用类型的属性被所有实例共享
- 可以在Child中向Parent传参
缺点:
- 方法都在构造函数中定义,每次创建实例都会创建一次方法
3.组合继承(原型链继承+构造函数继承)
function Parent(name) {
this.name = name;
}
Parent.prototype.getName = function () {
console.log(this.name);
}
function Child (name) {
Parent.call(this, name)
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child1 = new Child('kevin');
优点: 融合原型链继承和构造函数的优点,是 JavaScript 中最常用的继承模式。
缺点: 会调用两次父构造函数
4.原型式继承(将传入的对象作为创建的对象的原型)
function creatObj(o) {
function F() {}
F.prototype = o;
return new F();
}
缺点: 包含引用类型的属性值始终都会共享相应的值,这点跟原型链继承一样。
如:
var person = {
name: 'kevin',
friends: ['daisy', 'kelly']
}
var person1 = createObj(person);
var person2 = createObj(person);
person1.name = 'person1';
console.log(person2.name); // kevin
person1.friends.push('taylor');
console.log(person2.friends); // ["daisy", "kelly", "taylor"]
5. 寄生式继承
function createObj(o) {
var clone = Object.create(o);
clone.sayName = function () {
console.log('hi');
}
return clone;
}
缺点:跟借用构造函数模式一样,每次创建对象都会创建一遍方法。
6.寄生组合式继承(最好的继承方法)
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;
}
// 关键的三步
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
var child1 = new Child('kevin', '18');
console.log(child1);
封装一下,变成:
function creatObj(o) {
function F() {}
F.prototype = o;
return new F();
}
function prototype(child, parent) {
var prototype = creatObj(parent.prototype)
prototype.constructor = child;
child.prototype = prototype;
}
//调用
prototype(Child, Parent);
优点:
- 只调用了一次 Parent 构造函数
- 避免了在 Parent.prototype 上面创建不必要的、多余的属性
- 原型链还能保持不变,因此,还能够正常使用 instanceof 和 isPrototypeOf