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

本文共 1891 字,大约阅读时间需要 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); // 11console.log(man.name); // '小王'man.run(); // '我很能跑'let man2 = new Man('33');console.log(man2.age); // 33console.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); // 12man1.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); // 12man1.eat(); // '吃饭'man1.run(); // '我很能跑'let man2 = new Man('大王', 21);console.log(man2.name); // '大王'console.log(man2.age); // 21man2.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/

你可能感兴趣的文章
NOIP2014 提高组 Day2——寻找道路
查看>>
NOIp模拟赛二十九
查看>>
Nokia5233手机和我装的几个symbian V5手机软件
查看>>
Non-final field ‘code‘ in enum StateEnum‘
查看>>
none 和 host 网络的适用场景 - 每天5分钟玩转 Docker 容器技术(31)
查看>>
None还可以是函数定义可选参数的一个默认值,设置成默认值时实参在调用该函数时可以不输入与None绑定的元素...
查看>>
NOPI读取Excel
查看>>
NoSQL&MongoDB
查看>>
NoSQL介绍
查看>>
Notepad ++ 安装与配置教程(非常详细)从零基础入门到精通,看完这一篇就够了
查看>>
Notepad++在线和离线安装JSON格式化插件
查看>>
notepad++最详情汇总
查看>>
notepad如何自动对齐_notepad++怎么自动排版
查看>>
Notification 使用详解(很全
查看>>
NotImplementedError: Cannot copy out of meta tensor; no data! Please use torch.nn.Module.to_empty()
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>