前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >JavaScript进阶:组合式继承和寄生组合式继承

JavaScript进阶:组合式继承和寄生组合式继承

作者头像
用户7043603
发布2022-02-26 11:38:35
8950
发布2022-02-26 11:38:35
举报
1、组合式继承

组合继承了使用原型链实现对原型属性和方法的继承,同时配合使用构造函数继承实现对实例属性的继承。以免导致多个实例对引用类型的数据共享一份数据。理论上解决了之前继承方式带来的问题。

代码语言:javascript
复制
// 创建父类
function ParentClass(name) {
    this.name = name;
}
// 在父类原型上添加方法
ParentClass.prototype.getName = function() {
    console.log(this.name);
}
// 创建子类
function ChildClass(name, time) {
    this.time = time;
    ParentClass.call(this, name);
}
// 将父类赋值给子类实例
ChildClass.prototype = new ParentClass('lisi');
// 在子类原型上添加方法
ChildClass.prototype.getTime = function() {
    console.log(this.time);
}
const child = new ChildClass('zhangsan', '2022-01-12');
child.getName();  // zhangsan
child.getTime();    //  2022-01-12
console.log(child instanceof ParentClass)  // true
console.log(child instanceof ChildClass)    // true
console.log(ChildClass.prototype);   //  ParentClass {name: 'lisi', getTime: ƒ}

这种继承方式同样并不完美,存在重复调用了父类的构造函数,第一次在ParentClass中的name属性写入到ChildClass的prototype原型上去,第二次执行的构造函数是在子类实例化的时候,又执行了父类的构造函数,又将ParentClass中的name属性写入到ChildClass的prototype原型上去。这样就导致了没必要的重复操作。

代码语言:javascript
复制
// 创建父类
function ParentClass(name) {
    this.name = name;
    console.log('执行了一次父类的构造函数')
}

可以看出来,组合式继承执行了两次父类的构造函数,重复无用的操作我们应当需要进行避免。

2、寄生组合式继承

使用Object.create()使得新创建的对象保持指向ParentClass的原型对象ChildClass.prototype = Object.create(ParentClass.prototype); 在MDN中对其进行了解释说明,Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__

代码语言:javascript
复制
// 创建父类
function ParentClass(name) {
    this.name = name;
    console.log('执行了一次父类的构造函数')
}
// 在父类原型上添加方法
ParentClass.prototype.getName = function() {
    console.log(this.name);
}
// 创建子类
function ChildClass(name, time) {
    this.time = time;
    ParentClass.call(this, name);
}
// 使用Object.create()使得新创建的对象保持指向ParentClass的原型对象
ChildClass.prototype = Object.create(ParentClass.prototype);
console.log(ChildClass, Object.create(ParentClass.prototype));
// 在子类原型上添加方法
ChildClass.prototype.getTime = function() {
    console.log(this.time);
}
const child = new ChildClass('zhangsan', '2022-01-12');
child.getName();
child.getTime();
console.log(child instanceof ParentClass)
console.log(child instanceof ChildClass)
console.log(ChildClass.prototype);

这样在父类中打印是只执行了一遍父类的构造函数,这样就弥补了组合式继承的缺点。

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1、组合式继承
  • 2、寄生组合式继承
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档