继承

94 阅读1分钟

原型链继承

原型原型链 戳这里

function Parent () {
 this.name = "张三"
}

Parent.prototype.getName = function () {
  console.log(this.name)
}

function Child () {}

Child.prototype = new Parent ();

let child = new Child();

console.log(child.getName())   // 张三

image.png

缺点:

  • 构造函数可以创建多个实例,引用类型的属性会被所有实例共享,以数组为例;

  • 在创建 Child 的实例的时候,不能向 Parent 传递参数;

function Parent () {
 this.name = ['张三','李四'];
}

function Child () {}

Child.prototype = new Parent();

let child1 = new Child();

child1.name.push('王五');  // ['张三', '李四', '王五']

console.log(child1.name);

let child2 = new Child();

console.log(child2.name);  // ['张三', '李四', '王五']

image.png

构造函数继承

function Parent () {
 this.name = ['张三','李四'];
}

function Child () {
  Parent.call(this,name);
}

let child1 = new Child();

child1.name.push('王五');  

console.log(child1.name);  // ['张三', '李四', '王五']

let child2 = new Child();

console.log(child2.name);  // ['张三', '李四']

image.png

使用构造函数继承就可以解决使用原型链继承的缺点,但是由于方法都在构造函数中定义,所以每次创建实例的时候都会创建一次方法

组合继承

为解决原型链继承和构造函数继承的缺点,我们可以考虑同时使用原型链继承和构造函数继承,也就是组合继承。

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();
Child.prototype.constructor = Child;

let child1 = new Child('张三', '18');
child1.colors.push('black');
console.log(child1.name); 
console.log(child1.age); 
console.log(child1.colors); 

let child2 = new Child('李四', '20');
console.log(child2.name); 
console.log(child2.age); 
console.log(child2.colors); 

image.png