博客
关于我
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. 借用构造函数继承

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

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/

你可能感兴趣的文章
Python接口自动化测试实战系列
查看>>
python下载_安装_配置_以及第一行python程序---python工作笔记009
查看>>
Python不协调机器人消息.内容
查看>>
Python与C#之间内存共享互传信息
查看>>
python与c语言混合编程_你试过C语言和Python一起混合编程吗?两者相加不是已经无敌了!...
查看>>
python与excel
查看>>
Python与Excel的完美邂逅:深入浅出,手把手教你轻松玩转Excel数据操作
查看>>
python与flask_Python编程中flask的简介与简单使用
查看>>
python与图灵机器人交互(WXPY版本)
查看>>
python与运算符_python运算符
查看>>
python两个列表获取交集,并集,差集
查看>>
python两个字典合并,两个list合并
查看>>
Python两个版本共存时,命令行升级pip
查看>>
Python两个版本共存时,怎么验证是否安装成功 scrapy
查看>>
Python两个版本共存时,通过pip安装Scrapy
查看>>
python两组变量的相关关系散点图_变量是什么?变量间的两种关系——函数关系和相关关系(小学版)...
查看>>
Python中 pass语句的作用
查看>>
python中 urllib, urllib2, httplib, httplib2 几个库的区别
查看>>
python中 yaml库 & json库 & xmltodict库使用
查看>>
python中 将你的名字转化成为二进制并输出
查看>>