JavaScript super关键字

When we work with classes in JavaScript, it’s common to use the super keyword.

当我们使用JavaScript处理类时,通常使用super关键字。

In this post I want to clarify what’s it useful for.

在这篇文章中,我想阐明它的作用。

Suppose you have a class Car:

假设您有一个Car类:

class Car {

}

and in this class we have a constructor() method:

在这个类中,我们有一个constructor()方法:

class Car {
  constructor() {
    console.log('This is a car')
  }
}

The constructor method is special because it is executed when the class is instantiated:

构造函数方法很特殊,因为它在实例化类时执行:

const myCar = new Car() //'This is a car'

You can have a Tesla class that extends the Car class:

您可以拥有扩展Car类的Tesla类:

class Tesla extends Car {

}

The Tesla class inherited all the methods and properties of Car, including the constructor method.

Tesla类继承了Car所有方法和属性,包括constructor方法。

We can create an instance of the Tesla class, creating a new myCar object:

我们可以创建Tesla类的实例,创建一个新的myCar对象:

const myCar = new Tesla()

And the original constructor in Car is still executed, because Tesla does not have one of its own.

Car的原始构造函数仍在执行,因为Tesla没有自己的构造函数。

We can override the constructor() method in the Tesla class:

我们可以在Tesla类中重写constructor()方法:

class Tesla extends Car {
  constructor() {
    console.log('This is a Tesla')
  }
}

and

const myCar = new Tesla()

will print This is a Tesla.

将打印This is a Tesla

In the constructor() method we can also call super() to invoke the same method in the parent class:

constructor()方法中,我们还可以调用super()来调用父类中的相同方法:

class Tesla extends Car {
  constructor() {
    super()
    console.log('This is a Tesla')
  }
}

Calling

呼唤

const myCar = new Tesla()

will now execute 2 console logs. First the one defined in the Car class constructor, the second the one defined in the Tesla class constructor:

现在将执行2个控制台日志。 第一个是在Car类构造函数中定义的,第二个是在Tesla类构造函数中定义的:

'This is a car'
'This is a Tesla'

Note that super() can only be called in the constructor, not in other methods.

请注意,只能在构造函数中调用super() ,而不能在其他方法中调用。

And we can pass in any parameter, if the constructor accepts parameters.

如果构造函数接受参数,我们可以传入任何参数。

翻译自: https://flaviocopes.com/javascript-super/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值