组合继承了使用原型链实现对原型属性和方法的继承,同时配合使用构造函数继承实现对实例属性的继承。以免导致多个实例对引用类型的数据共享一份数据。理论上解决了之前继承方式带来的问题。
// 创建父类
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原型上去。这样就导致了没必要的重复操作。
// 创建父类
function ParentClass(name) {
this.name = name;
console.log('执行了一次父类的构造函数')
}
可以看出来,组合式继承执行了两次父类的构造函数,重复无用的操作我们应当需要进行避免。
使用Object.create()使得新创建的对象保持指向ParentClass的原型对象ChildClass.prototype = Object.create(ParentClass.prototype);
在MDN中对其进行了解释说明,Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__
。
// 创建父类
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 删除。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有