博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Javascript组合继承模式和寄生式组合继承的区别
阅读量:4162 次
发布时间:2019-05-26

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

组合继承

function Parent (name) {    this.name = name;    this.colors = ['red', 'blue', 'green'];}Parent.prototype.getName = function () {    console.log(this.name)}function Child (name, age) {    Parent.call(this, name);    this.age = age;}Child.prototype = new Parent();var child1 = new Child('kevin', '18');

console.log(child1)复制代码组合继承最大的缺点是会调用两次父构造函数。

一次是设置子类型实例的原型的时候:

Child.prototype = new Parent();

一次在创建子类型实例的时候:

var child1 = new Child('kevin', '18');

回想下 new 的模拟实现,其实在这句中,我们会执行:

Parent.call(this, name);

在这里,我们又会调用了一次 Parent 构造函数。

所以,在这个例子中,如果我们打印 child1 对象,我们会发现 Child.prototype 和 child1 都有一个属性为colors,属性值为[‘red’, ‘blue’, ‘green’]。

寄生式组合继承

function Parent (name) {    this.name = name;    this.colors = ['red', 'blue', 'green'];}Parent.prototype.getName = function () {    console.log(this.name)}function Child (name, age) {    Parent.call(this, name);    this.age = age;}function object(o) {    function F() {}    F.prototype = o;    return new F();    // 通过构造一个介于 Parent 与 Child 之间的对象,并使该对象的 prototype 属性指向 Parent 的 prototype对象,    // 来避开通过调用 Parent 构造函数的方式来产生一个 prototype 指向Parent prototype对象的对象。}function prototype(child, parent) {// 不直接child.prototype=parent.prototype呢?// 原因 : 当我们想给 Child 的prototype里面添加共享属性或者方法时,如果其 prototype 指向的是 Parent 的 prototype,那么在 Child 的 prototype 里添加的属性和方法也会反映在 Parent 的 prototype 里面,// 这明显是不合理的,这样做的后果是当我们只想使用 Parent 时,也能看见 Child 往里面扔的方法和属性。// 所以需要每个构造函数都需要持有自己专用的prototype对象    var prototype = object(parent.prototype);    prototype.constructor = child;    child.prototype = prototype;}prototype(Child, Parent);var child1 = new Child('kevin', '18');console.log(child1);

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

你可能感兴趣的文章
【Python】学习笔记——-7.3、继承和多态
查看>>
【Python】学习笔记——-7.5、实例属性和类属性
查看>>
git中文安装教程
查看>>
虚拟机 CentOS7/RedHat7/OracleLinux7 配置静态IP地址 Ping 物理机和互联网
查看>>
Jackson Tree Model Example
查看>>
常用js收集
查看>>
如何防止sql注入
查看>>
springmvc传值
查看>>
在Eclipse中查看Android源码
查看>>
Android使用webservice客户端实例
查看>>
[转]C语言printf
查看>>
C 语言 学习---回调、时间定时更新程序
查看>>
Single Number II --出现一次的数(重)
查看>>
对话周鸿袆:从程序员创业谈起
查看>>
Mysql中下划线问题
查看>>
Xcode 11 报错,提示libstdc++.6 缺失,解决方案
查看>>
vue项目打包后无法运行报错空白页面
查看>>
Vue 解决部署到服务器后或者build之后Element UI图标不显示问题(404错误)
查看>>
element-ui全局自定义主题
查看>>
facebook库runtime.js
查看>>