JavaScript中的继承

JavaScript中的继承可以通过原型链和类的方式实现。

        原型链继承: 原型链继承是JavaScript中最基本的继承方式,通过将父类的实例作为子类的原型,实现属性和方法的继承。

function Parent() {
  this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
  console.log('Hello from Parent');
};

function Child() {
  this.age = 10;
}
Child.prototype = new Parent();

var child = new Child();
child.sayHello(); // 输出 'Hello from Parent'
console.log(child.name); // 输出 'Parent'

通过将Child的原型指向Parent的实例,Child就可以继承Parent的属性和方法。

        构造函数继承: 构造函数继承是通过在子类的构造函数中调用父类的构造函数,实现属性的继承。

function Parent() {
  this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
  console.log('Hello from Parent');
};

function Child() {
  Parent.call(this);
  this.age = 10;
}

var child = new Child();
child.sayHello(); // 报错,sayHello不是继承自Parent的
console.log(child.name); // 输出 'Parent'

使用Parent.call(this)可以在子类构造函数中调用父类构造函数,从而继承父类的属性。

        组合继承: 组合继承是将原型链继承和构造函数继承结合起来,通过分别调用父类构造函数和设置子类原型实现属性和方法的继承。

function Parent() {
  this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
  console.log('Hello from Parent');
};

function Child() {
  Parent.call(this);
  this.age = 10;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;

var child = new Child();
child.sayHello(); // 输出 'Hello from Parent'
console.log(child.name); // 输出 'Parent'

使用Parent.call(this)继承父类的属性,使用Child.prototype = new Parent()继承父类的方法。需要注意的是,需要将子类原型的构造函数重新指向子类本身,以避免构造函数被重写。

        ES6类继承: ECMAScript 6中引入了类的概念,可以通过extends关键字来实现类的继承。

class Parent {
  constructor() {
    this.name = 'Parent';
  }
  sayHello() {
    console.log('Hello from Parent');
  }
}

class Child extends Parent {
  constructor() {
    super();
    this.age = 10;
  }
}

var child = new Child();
child.sayHello(); // 输出 'Hello from Parent'
console.log(child.name); // 输出 'Parent'

使用extends关键字来继承父类,使用super关键字来调用父类的构造函数和方法。

以上是JavaScript中实现继承的几种方式,可以根据需求和场景选择适合的方式

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

勇敢的茂密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值