构造函数和继承

本文详细介绍了JavaScript中三种常见的继承实现方式:原型继承、call继承以及ES6的类继承。通过实例代码展示了如何创建子类并继承父类的属性和方法。无论是使用子类原型等于父类实例,还是通过call方法,或者是利用ES6的class关键字和super关键字,都能实现不同形式的继承。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

属性继承的几种方式

1.原型继承:让子类的原型等于父类的实例,代码如下:

function Parent1() {
  this.x = 100;
}
Parent1.prototype.getx = function getx() {
  return this.x
}

function Child1() {
  this.y = 200
}
Child1.prototype = new Parent1
var c1 = new Child1()
console.log(c1.x)
console.log(c1.y)

2.call继承:只能继承父类中私有的,不能继承父类中共有的,代码如下:

function Parent2() {
  this.x = "100x"
}
Parent2.prototype.getx = function getx() {
  return this.x
}

function Child2() {
  Parent2.call(this)
  this.y = "200y"
}
Child2.prototype.gety = function gety() {
  return this.y
}
var c2 = new Child2()
console.log(c2.x)
console.log(c2.y)

3.es6中的类和继承,代码如下:

class Parent3 {
  constructor() {
    this.x = 100
  }
  getx() {
    return this.x
  }
}
class Child3 extends Parent3 {
  constructor() {
    super()
    this.y = 200
  }
  gety() {
    return this.y
  }
}
var c3 = new Child3;
console.log(c3.x)
console.log(c3.y)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值