博客
关于我
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/

你可能感兴趣的文章
TCP基本入门-简单认识一下什么是TCP
查看>>
tableviewcell 中使用autolayout自适应高度
查看>>
Symbolic Aggregate approXimation(SAX,符号聚合近似)介绍-ChatGPT4o作答
查看>>
Orcale表被锁
查看>>
svn访问报错500
查看>>
sum(a.YYSR) over (partition by a.hy_dm) 不需要像group by那样需要分组函数。方便。
查看>>
ORCHARD 是什么?
查看>>
Struts2中使用Session的两种方法
查看>>
Stream API:filter、map和flatMap 的用法
查看>>
STM32工作笔记0032---编写跑马灯实验---寄存器版本
查看>>
Static--用法介绍
查看>>
ssm旅游信息管理系统的设计与实现bus56(程序+开题)
查看>>
order by rand()
查看>>
SSM(Spring+SpringMvc+Mybatis)整合开发笔记
查看>>
ViewHolder的改进写法
查看>>
Orderer节点启动报错解决方案:Not bootstrapping because of 3 existing channels
查看>>
org.apache.axis2.AxisFault: org.apache.axis2.databinding.ADBException: Unexpected subelement profile
查看>>
sql查询中 查询字段数据类型 int 与 String 出现问题
查看>>
org.apache.commons.beanutils.BasicDynaBean cannot be cast to ...
查看>>
org.apache.dubbo.common.serialize.SerializationException: com.alibaba.fastjson2.JSONException: not s
查看>>