五种继承方式

五种继承方式

1. 原型继承

function A() {
  this.x = 100;
}
A.prototype.getX = function () {
  console.log(this.x);
};
function B() {
  this.y = 200;
}
B.prototype = new A
var b = new B;
console.log(b)

子类B想要继承父类A中的所有属性和方法(私有和公有),只需要让B.prototype=new A;
特点:它是把父类中私有的和公有的都继承到子类原型上
原型继承并不是把父类中的属性和方法克隆一份一模一样的给B,而是让B和A之间增加了原型链的连接,以后B的实例b想要A中的的getX方法,需要一级级的向上查找来使用,通过_ proto _子类可以改变父类的属性和方法

2. call继承

function B() {
  // this -> b
  A.call(this); // ->A.call(b) 把A执行让A中的this变为b
}
var b = new B;
console.log(b.x) // 100
console.log(b.getX()) // TypeError: b.getX is not a function

call继承把父类私有的属性和方法克隆一份一模一样的作为子类私有的属性

3. 冒充对象继承

function A() {
  this.x = 100;
}
A.prototype.getX = function () {
  console.log(this.x);
};
function B() {
  // this -> b
  var temp = new A;
  for (var key in temp) {
    this[key] = temp[key];
  }
  temp = null;
}
var b = new B;
console.log(b)

把父类的私有的和公有的克隆一份一模一样的给子类私有的

4. 混合模式继承

原理:原型继承+ call继承

function A() {
  this.x = 100;
}
A.prototype.getX = function () {
  console.log(this.x);
};
function B() {
    A.call(this) // -> n.x = 100
}
B.prototype = new A; // -> B.prototype: x=100,getX
B.prototype.constructor = B;
var b = new B;
b.getX();

这种继承方式,会导致私有属性和公有属性重复

5.寄生组合式继承

私有的继承私有的(通过call)
公有的继承公有的(prototype上的继承prototype的,通过Object.create() )

function A() {
  this.x = 100;
}
A.prototype.getX = function () {
  console.log(this.x);
};
function B() {
    A.call(this)
}
B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;
var b = new B;
b.getX();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值