A class can extend another class, and objects initialized using that class inherit all the methods of both classes.
Suppose we have a class Person
:
class Person {
hello() {
return 'Hello, I am a Person'
}
}
We can define a new class Programmer
that extends Person
:
class Programmer extends Person {
}
Now if we instantiate a new object with class Programmer
, it has access to the hello()
method:
const flavio = new Programmer()
flavio.hello() //'Hello, I am a Person'
The JavaScript instanceof operator returns true if the first operand is an instance of the object passed on the right, or has it in its inheritance chain.
In this example you can see that the myCar object, of class Fiesta, responds true to instanceof Fiesta, and also responds true to instanceOf Car, because Fiesta extends Car:
class Car {}
class Fiesta extends Car {}
const myCar = new Fiesta()
myCar instanceof Fiesta //true
myCar instanceof Car //also true
In the constructor()
method we can also call super()
to invoke the same method in the parent class.
Suppose you have a class Car
:
class Car {
}
and in this class we have a constructor()
method:
class Car {
constructor() {
console.log('This is a car')
}
}
You can have a Tesla
class that extends the Car
class:
class Tesla extends Car {
}
The Tesla
class inherited all the methods and properties of Car
, including the constructor
method.
We can create an instance of the Tesla
class, creating a new myCar
object:
const myCar = new Tesla()
The original constructor in Car
is executed, because Tesla
does not have one of its own.
We can override the constructor()
method in the Tesla
class:
class Tesla extends Car {
constructor() {
console.log('This is a Tesla')
}
}
and
const myCar = new Tesla()
will print This is a Tesla
.
In the constructor()
method we can call super()
to invoke the same method in the parent class:
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:
'This is a car'
'This is a Tesla'
Note that super()
can only be called in the constructor, not in other methods.
And we can pass in any parameter to the parent class, if the constructor accepts parameters.
Lessons this unit:
0: | Introduction |
1: | Classes |
2: | Class methods |
3: | Private class properties |
4: | Constructors |
5: | ▶︎ Inheritance |
6: | Prototypes |