博客
关于我
js之继承
阅读量:198 次
发布时间:2019-02-28

本文共 1946 字,大约阅读时间需要 6 分钟。

什么是继承

继承是类与类之间的关系,其主要作用是使子类能够继承父类的属性和方法。通过继承,可以在子类中重复使用父类的功能,避免代码冗余。


继承的实现方式

继承的实现方式主要有四种:原型链继承、借用构造函数继承、组合继承以及原型式继承。每种方法都有其独特的特点和适用场景。

1. 原型链继承

原型链继承的核心思想是让新实例的原型等于父类的实例。这种方法通过重新赋值 prototype 属性来实现继承。

function Human(name) {
this.name = name;
this.eat = function() {
console.log('吃饭');
};
}
Human.prototype.run = function() {
console.log('我很能跑');
};
// 实现继承
function Man(age) {
this.age = age;
}
Man.prototype = new Human('小王');
// 创建实例
let man = new Man('11');
console.log(man.age); // 11
console.log(man.name); // '小王'
man.run(); // '我很能跑'
let man2 = new Man('33');
console.log(man2.age); // 33
console.log(man2.name); // '小王'
man2.run(); // '我很能跑'

优点

  • 实现了属性的共享,减少内存占用。

缺点

  • 新实例无法传递父类构造函数的参数。
  • 仅支持单一继承,无法实现多个接口的继承。

2. 借用构造函数继承

借用构造函数继承通过调用 callapply 方法,将父类的构造函数引入子类,从而实现继承。

function Man(name, age) {
Human.call(this, name);
this.age = age;
}
// 创建实例
let man1 = new Man('小王', 12);
console.log(man1.name); // '小王'
console.log(man1.age); // 12
man1.eat(); // '吃饭'
let man2 = new Man('大王', 21);
console.log(man2.name); // '大王'
console.log(man2.age); // 21

优点

  • 可以传递构造函数的参数。

缺点

  • 每次创建实例都需要重新调用父类构造函数,导致内存占用增加。

3. 组合继承

组合继承结合了原型链继承和借用构造函数继承的优点,既能传递参数,又能继承原型链上的属性。

function Man(name, age) {
Human.call(this, name);
this.age = age;
}
Man.prototype = new Human();
// 创建实例
let man1 = new Man('小王', 12);
console.log(man1.name); // '小王'
console.log(man1.age); // 12
man1.eat(); // '吃饭'
man1.run(); // '我很能跑'
let man2 = new Man('大王', 21);
console.log(man2.name); // '大王'
console.log(man2.age); // 21
man2.run(); // '我很能跑'

优点

  • 允许传递构造函数的参数。
  • 维护原型链上的属性和方法。

缺点

  • 子类构造函数会覆盖原型链上的父类构造函数。

4. 原型式继承

原型式继承通过创建一个函数来包装对象,然后返回新对象,使其继承原型链上的属性。

function Man(obj) {
function F() {}
F.prototype = obj;
return new F();
}
// 创建实例
let human = new Human('小');
let man = Man(human);
console.log(man.name); // '小'

优点

  • 适合需要频繁修改原型链属性的情况。

缺点

  • 每个实例都有独立的属性,无法实现构造函数的复用。

web前端技术交流QQ群:327814892

如果你对前端技术感兴趣,可以加入我们的交流群,和技术大牛一起探讨更多有趣的内容!

转载地址:http://ktri.baihongyu.com/

你可能感兴趣的文章