js继承

原型链继承

function SubType(){
	this.property = true;
}
SubType.prototype.get = function(){
	return this.property;
}
function SuperType(){
}
SuperType.prototype = new SubType();
var ins = new SuperType();

在这里插入图片描述
缺点:

  • 所有子类的实例对引用类型的操作会共享
  • 子类型的原型上的constructor指向的是父类的构造函数
  • 给子类型添加方法必须在替换子类原型后
  • 创建子类型时无法向父类传参

借助构造函数继承

function SubType(){
	this.property = true;
}
SubType.prototype.get = function(){
	return this.property;
}
function SuperType(){
	SuperType.call(this);	
}
var ins = new SuperType();

优点:

  • 可以给父类传参,并且不会重写子类的原型。
    缺点
  • 无法继承原型上的属性和方法。

组合继承

function SubType(name){
	this.property = name;
}
SubType.prototype.get = function(){
	return this.property;
}
function SuperType(name){
	SuperType.call(this, name);	//第二次调用父类
}
SuperType.prototype = new SubType(); //第一次调用父类,不用传参,第二次调用会覆盖第一次的实力属性
SuperType.prototype.constructor = SuperType;
var ins = new SuperType("a");

优点:

  • 成功继承到父类的属性和方法。
    缺点:
  • 调用两次父类,

原型式继承

function object(proto) {
  function F() {}
  F.prototype = proto;
  return new F();
}

const cat = {
  name: 'Lolita',
  friends: ['Yancey', 'Sayaka', 'Mitsuha'],
  say() {
    console.log(this.name);
  },
};

const cat1 = object(cat);

缺点:

  • 导致引用类型被多个实例篡改

寄生式继承

const cat = {
  name: 'Lolita',
  friends: ['Yancey', 'Sayaka', 'Mitsuha'],
  say() {
    console.log(this.name);
  },
};

function createAnother(original) {
  const clone = Object.create(original); // 获取源对象的副本

  clone.gender = 'female';

  clone.fly = function() {
    // 增强这个对象
    console.log('I can fly.');
  };

  return clone; // 返回这个对象
}

const cat1 = createAnother(cat);

缺点:

  • 引用类型被篡改,函数无法复用;

寄生组合式继承

function inheritPrototype(child, parent) {
  const prototype = Object.create(parent.prototype); // 创建父类原型的副本
  prototype.constructor = child; // 将副本的构造函数指向子类
  child.prototype = prototype; // 将该副本赋值给子类的原型
}


function Vehicle(powerSource) {
  this.powerSource = powerSource;
  this.components = ['座椅', '轮子'];
}

Vehicle.prototype.run = function() {
  console.log('running~');
};

function Car(wheelNumber) {
  this.wheelNumber = wheelNumber;
  Vehicle.call(this, '汽油');
}

inheritPrototype(Car, Vehicle);

Car.prototype.playMusic = function() {
  console.log('sing~');
};

只是记录学习,参考自这里

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值