JavaScript在 ES6 之前实现继承的几种方法

19 阅读1分钟
1. 原型链继承

优点:可以直接继承原型上的属性和方法
缺点:多个实例共享同一个原型对象,修改互相之前有影响;没办法向构造函数传参

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

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

Child.protoType = new Parent();
var child = new Child();

console.log(child.parentProtoType) // true
  1. 构造函数继承
function parent(name){
    this.name = name;
}
function child(name) {
    parent.call(this, name);
}
var child1 = new Child('Child1');
console.log(child1.name) // 'Child1'