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.
如果构造函数接受参数,我们可以传入任何参数。