前端手撕代码——寄生组合式继承.js

文章介绍了JavaScript中一种组合构造函数和寄生式继承的方法——寄生组合式继承,通过parent和child两个构造函数,以及initPrototype函数来创建对象并继承父类的属性和方法。child1实例成功调用了sayName和getName方法,展示了继承的效果。
摘要由CSDN通过智能技术生成
//  寄生组合式继承,使用了构造函数 和 寄生式继承的方式


function parent(name){
  this.name = name;
  this.color = ['blue', 'red', 'grey'];
}


parent.prototype.getName = function(){
  console.log('父类实例方法——', this.name);
}

function child(name, theme){
  parent.call(this, name);
  this.theme = theme;
}

// 相当于使用child 替换掉了 parent的位置
function initPrototype(child, parent){
  let prototype = Object.create(parent.prototype);   // 创建对象,拿到父类实例的原型对象
  // 解绑原来的关系 绑定新关系
  prototype.constructor = child; 
  child.prototype = prototype;
}

initPrototype(child, parent);
child.prototype.sayName = function(){
  console.log('this.sayName', this.name);
}

let child1 = new child('123', 'color');
child1.sayName();
child1.getName();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值