js-继承的初步理解


//这是一个父类
function Father(fatherName) {
  this.fatherName = fatherName;
  this.fatherRole = ['a', 'b']
  if (typeof this.eat != "function") {
    Father.prototype.eat = function () {
      alert(this.fatherName)
    }
  }
}

1、原型链继承


function Son1() {
  this.sonName = '子类';
}

Son1.prototype = new Father('父类');//继承了父类的所有属性

let a1 = new Son1();
let a2 = new Son1();

console.log(a1.fatherName);//输出:父类
console.log(a1.sonName);//输出:子类
console.log(a1.fatherRole);//输出:['a','b']

a1.fatherRole.push('c');//改变a1对象中的fatherRole
console.log(a1.fatherRole);//输出:['a','b','c']
console.log(a2.fatherRole);//输出:['a','b','c']、此时 a2 对象也发生了改变

a1.eat();//弹出提示框

注:原型链继承的缺点
1、父类型的属性共享问题:子类型原型(父类型对象)中的属性被所有的子类型的实例所共有,如果有个一个实例去更改,则会很快反应的其他的实例上
2、向父类型的构造函数中传递参数问题:只有一个地方用到了父类型的构造函数,Son.prototype = new Father();。只能在这个一个位置传递参数,但是这个时候传递的参数,将来对子类型的所有的实例都有效

2、借用方式‘继承’


function Son2(name) {
  this.sonName = '子类';
  Father.call(this, name); //调用Father方法(看成普通方法),第一个参数传入一个对象this,则this(Son2类型的对象)就成为了Father中的this
}

let b1 = new Son2('父类1');
let b2 = new Son2('父类2');

console.log(b1.fatherName);//输出:父类1
console.log(b2.fatherName);//输出:父类2
console.log(b1.sonName);//输出:子类
console.log(b2.sonName);//输出:子类

b1.fatherRole.push('c');//改变b1对象中的fatherRole
console.log(b1.fatherRole);//输出:['a','b','c']
console.log(b2.fatherRole);//输出:['a','b']

b1.eat();//报错,找不到eat方法,因为Son2本身中没有这个方法

注:借用方式‘继承’的缺点
1、Father的原型对象中的共享属性和方法,Son没有办法获取。因为这个根本就不是真正的继承

3、组合继承


function Son3(name) {
  this.sonName = '子类';
  Father.call(this,name);
}
Son3.prototype = new Father();

let c1 = new Son3('父类1');
let c2 = new Son3('父类2');

console.log(c1.fatherName);//输出:父类1
console.log(c2.fatherName);//输出:父类2
console.log(c1.sonName);//输出:子类
console.log(c2.sonName);//输出:子类

c1.fatherRole.push('c');//改变c1对象中的fatherRole
console.log(c1.fatherRole);//输出:['a','b','c']
console.log(c2.fatherRole);//输出:['a','b']

c1.eat();//弹出提示框

注:组合继承
1、组合继承是我们实际使用中最常用的一种继承方式。
2、可能有个地方有些人会有疑问:Son.prototype = new Father( );这不照样把父类型的属性给放在子类型的原型中了吗,还是会有共享问题呀。但是不要忘记了,我们在子类型的构造函数中借调了父类型的构造函数,也就是说,子类型的原型(也就是Father的对象)中有的属性,都会被子类对象中的属性给覆盖掉。就是这样的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值