欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

升级你的JavaScript技能:探索组合式继承和寄生组合式继承的方法

最编程 2024-02-13 22:38:16
...
1、组合式继承

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

// 创建父类
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('执行了一次父类的构造函数')
}

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

2、寄生组合式继承

使用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);

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