<!DOCTYPE html>
<html lang="zh"> <head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>实现继承的5种方式(逐渐优化)</title>
</head> <body> <script type="text/javascript">
//方法1 使用构造函数
function Parent1(name) {
this.name = name || 'meng';
} function Child1(age) {
Parent1.call(this)
this.age = age;
}
let c1 = new Child1(20)
console.log(c1)
//方法2 使用原型
function Parent2(name) {
this.name = name || 'meng';
// 对于这种是有问题的,因为子类共用一个原型
this.friend = [1, 2, 3]
} function Child2(age) {
this.age = age;
}
//不能使用Parent2.prototype,否则c2.friend.push会报错,因为Parent2.prototype的原型上没有friend属性
//Child2.prototype = Parent2.prototype
Child2.prototype = new Parent2()
let c2 = new Child2(21)
let c3 = new Child2(22)
c2.friend.push(4)
console.log(c2)
console.log(c3)
//组合继承
function Parent3(name) {
this.name = name || 'meng';
this.friend = [1, 2, 3]
} function Child3(age) {
Parent3.call(this)
this.age = age;
}
Child3.prototype = new Parent3()
let c4 = new Child3(21)
let c5 = new Child3(22)
c4.friend.push(4)
console.log(c4)
console.log(c5)
//组合继承优化1 只调用一次构造函数
function Parent4(name) {
this.name = name || 'meng';
this.friend = [1, 2, 3]
} function Child4(age) {
Parent4.call(this)
this.age = age;
}
Child4.prototype = Parent4.prototype
let c6 = new Child4(21)
let c7 = new Child4(22)
c6.friend.push(4)
console.log(c6)
console.log(c7)
//组合继承优化2 使用Object.create
function Parent5(name) {
this.name = name || 'meng';
this.friend = [1, 2, 3]
} function Child5(age) {
Parent4.call(this)
this.age = age;
}
Child5.prototype = Object.create(Parent5.prototype)
Child5.prototype.constructor = Child5
let c8 = new Child5(21)
let c9 = new Child5(22)
c8.friend.push(4)
console.log(c8)
console.log(c9)
//es6
class Parent6 {
constructor(name) {
this.name = name || 'meng'
this.friend = [1, 2, 3]
}
} class Child6 extends Parent6 {
constructor(name, age) {
super(name);
this.age = age
}
}
let c10 = new Child6(21)
let c11 = new Child6(22)
c10.friend.push(4)
console.log(c10)
console.log(c11)
</script>
</body> </html>

其中第五种方法:

Object.create这种方式实现了将父类和子类的的原型完美分隔 。双方不会互相影响,也就是说这是确实可行较好的继承实现方式。

最新文章

  1. mysqldump
  2. UEditor的使用
  3. mvc5权限管理(简单登录):ActionFilterAttribute
  4. mysql主从切换摘要
  5. Intellij idea 设置svn 父目录文件显示状态颜色
  6. 头像上传功能实现,PC端的需要做兼容
  7. GNU make 升级
  8. Redis学习一 五种基本的数据类型
  9. spring webmvc使用ResponseBody前,在配置文件中的配置
  10. Android绘图之渐隐动画
  11. 自动回复消息-微信公众平台开发4(asp.net)
  12. POJ 1724 最短路费用限制
  13. linux查看系统的日志的一些实用操作
  14. OpenCV基础篇之画图及RNG随机数对象
  15. C# ASP.NET 转换为int型的方法 很实用
  16. 【洛谷2015】【CJOJ1976】二叉苹果树
  17. UVA10723 电子人的基因 Cyborg Genes
  18. 洛谷P4859 已经没有什么好害怕的了 [DP,容斥]
  19. mysql链接
  20. bower配置私服nexus3

热门文章

  1. C#里,如何模拟DataGridView里的一个Cell的Click事件。
  2. [Web 前端] webstorm 快速搭建react项目
  3. golang的Flag和Pflag
  4. java的反射机制浅谈(转)
  5. DatabaseMirroring搭建
  6. [leetcode]Anagrams @ Python
  7. AI 经典书单 | 人工智能学习该读哪些书
  8. 8天学通MongoDB——第一天 基础入门(转)
  9. 屌丝就爱尝鲜头——java8再判断
  10. VS2010自带的性能分析工具分析.NET程序的性能