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

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

一、什么是继承

继承是类与类之间的关系,其作用是使得子类具有父类别的各种属性和方法。

二、继承的实现方式

想要继承,就必须要提供个父类(继承谁,提供继承的属性)

// 创建一个人类,并且人类带有名字 吃饭和能跑的属性function Human(name) {         this.name = name      this.eat = function () {           console.log('吃饭')      }    }    Human.prototype.run = function () {         console.log('我很能跑')    }
1.原型链继承(重点:让新实例的原型等于父类的实例。)
// 创建一个男人类,并且让男人类 继承 人类有名字 吃饭和能跑的属性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.借用构造函数继承(重点:用.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) // 12    man1.eat() // 吃饭    man1.run() // Uncaught TypeError: man1.run is not a function    let man2 = new Man('大王', 21)    console.log(man2.name) // 大王    console.log(man2.age) // 21

缺点:

  • 只能继承父类构造函数的属性。
  • 无法实现构造函数的复用。(每次用每次都要重新调用)
  • 每个新实例都有父类构造函数的副本,臃肿。
3.组合继承(组合原型链继承和借用构造函数继承)(常用)
function Man(age, name) {         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

优点:

  • 可以继承父类原型上的属性,可以传参,可复用。

缺点:

  • 调用了两次父类构造函数(耗内存),子类的构造函数会代替原型上的那个父类构造函数。
4.原型式继承(用一个函数包装一个对象,然后返回这个函数的调用,这个函数就变成了个可以随意增添属性的实例或对象。object.create()就是这个原理。)
function Man(obj) {         function F() {   }      F.prototype = obj      return new F()    }    let man = new Human('小')    let man1 = Man(man)    console.log(man1.name) // 小

缺点:

  • 所有实例都会继承原型上的属性。
  • 无法实现复用。(新实例属性都是后面添加的)

web前端技术交流QQ群:327814892

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

你可能感兴趣的文章
Nginx + Tomcat + SpringBoot 部署项目
查看>>
Nginx + uWSGI + Flask + Vhost
查看>>
Nginx - Header详解
查看>>
nginx - thinkphp 如何实现url的rewrite
查看>>
Nginx - 反向代理、负载均衡、动静分离、底层原理(案例实战分析)
查看>>
Nginx - 反向代理与负载均衡
查看>>
nginx 1.24.0 安装nginx最新稳定版
查看>>
nginx 301 永久重定向
查看>>
nginx 301跳转
查看>>
nginx 403 forbidden
查看>>
nginx connect 模块安装以及配置
查看>>
nginx css,js合并插件,淘宝nginx合并js,css插件
查看>>
Nginx gateway集群和动态网关
查看>>
nginx http配置说明,逐渐完善。
查看>>
Nginx keepalived一主一从高可用,手把手带你一步一步配置!
查看>>
Nginx Location配置总结
查看>>
Nginx log文件写入失败?log文件权限设置问题
查看>>
Nginx Lua install
查看>>
nginx net::ERR_ABORTED 403 (Forbidden)
查看>>
vue中处理过内存泄露处理方法
查看>>