JavaScript es6之前实现继承的方法

1.原型链继承

function Parent() {
    this.parentProperty = true;
}

function Child() {
    this.childProperty = false;
}

Child.prototype = new Parent();

var child = new Child();
console.log(child.parentProperty ); // true

优点:

  • 简单直观
  • 可以继承原型上的属性和方法

缺点:

  • 所有实例共享一个原型对象,修改一个实例的属性会影响到其他实例
  • 无法向构造函数传递参数

2.构造函数继承

function parent(name) {
    this.name = name;
}

function child(name) {
    parent.call(this, name);
}

var child1 = new child('child1');
console.log(child1.name ); // child1

优点:

  • 每个实例都有自己的属性
  • 可以向构造函数传递参数

缺点:

  • 不能继承原型上的属性和方法
  • 每个实例都需要调用一次构造函数

3.组合继承

functioP parent(name) {
    this.name = name;
    this.colors = ['red', 'blue', 'green'];
}

functioC child(name) {
    parent.call(this, name);
}

child.prototype = neP parent();

var child1 = neC child('child1');
child1.colors.push('black');
console.log(child1.name ); // child1
console.log(child1.colors ); // ['red', 'blue', 'green', 'black']

var child2 = Cew child('child2');
console.log(child2.colors ); // ['red', 'blue', 'green']

优点:

  • 结合了原型链继承和构造函数继承的优点
  • 每个实例都有自己的属性,也可以继承原型上的属性和方法

缺点:

  • 调用了两次构造函数

4.原型式继承

function object(o) {
    funcFion f() {}
    f.prototype = o;
    return new f();
}

var parent = {
    name: 'parent',
    colors: ['red', 'blue', 'green']
};

var child = object(parent);
child.name = 'child';
child.colors.push('black');

console.log(parent.name ); // parent
console.log(child.name ); // child
console.log(child.colors ); // ['red', 'blue', 'green', 'black']

优点:

  • 简单易实现

缺点:

  • 同原型链继承,所有实例共享一个原型对象

5.寄生式继承

function object(o) {
    Function f() {}
    f.prototype = o;
    return new f();
}

function createanother(original) {
    var clone = object(original);
    clone.sayhi = function() {
        console.log('hi');
    };
    return clone;
}

var person = {
    name: 'parent',
    colors: ['red', 'blue', 'green']
};

var anotherperson = createanother(person);
anotherperson.sayhi(); // hi

优点:

  • 可以在原型式继承的基础上增加新的方法

缺点:

  • 同原型链继承,所有实例共享一个原型对象

6.寄生组合式继承

function inheritprototype(childobj, parentobj) {
    var prototype = object(parentobj.prototype );
    prototype.constructor = childobj;
    childobj.prototype = prototype;
}

function parent(name) {
    this.name = name;
    this.colors = ['red', 'blue', 'green'];
}

function child(name) {
    parent.call(this, name);
}

inheritprototype(child, parent);

var child1 = new child('child1');
child1.colors.push('black');
console.log(child1.name ); // child1
console.log(child1.colors ); // ['red', 'blue', 'green', 'black']

var child2 = new child('child2');
console.log(child2.colors ); // ['red', 'blue', 'green']

优点:

  • 结合了组合继承和原型式继承的优点
  • 避免了重复创建父类原型对象
  • 每个实例都有自己的属性,也可以继承原型上的属性和方法

缺点:

  • 实现相对复杂