JavaScript로 클래스를 사용할 때 super 키워드를 사용하는 것이 일반적입니다.
이 게시물에서는 유용한 것이 무엇인지 명확히 하고 싶습니다.
클래스 Car가 있다고 가정하십시오.
class Car {
}
이 클래스에는 constructor() 메소드가 있습니다 :
class Car {
constructor() {
console.log('This is a car')
}
}
생성자 메서드는 클래스가 인스턴스화 될 때 실행되므로 특별합니다.
const myCar = new Car() //'This is a car'
Car 클래스를 확장하는 Tesla 클래스를 사용할 수 있습니다.
class Tesla extends Car {
}
Tesla 클래스는 생성자 메서드를 포함하여 Car의 모든 메서드와 속성을 상속했습니다.
Tesla 클래스의 인스턴스를 만들어 새로운 myCar 객체를 만들 수 있습니다.
const myCar = new Tesla()
Tesla에는 자체 생성자가 없으므로 Car의 원래 생성자는 여전히 실행됩니다.
Tesla 클래스에서 constructor() 메서드를 재정의 할 수 있습니다.
class Tesla extends Car {
constructor() {
console.log('This is a Tesla')
}
}
const myCar = new Tesla()
이것은 테슬라입니다.
constructor() 메서드에서 super()를 호출하여 부모 클래스에서 동일한 메서드를 호출 할 수도 있습니다.
class Tesla extends Car {
constructor() {
super()
console.log('This is a Tesla')
}
}
const myCar = new Tesla()
이제 2 개의 콘솔 로그가 실행됩니다. 첫 번째는 Car 클래스 생성자에 정의 된 것이고, 두 번째는 Tesla 클래스 생성자에 정의 된 것입니다.
'This is a car'
'This is a Tesla'
super()는 다른 메소드가 아닌 생성자에서만 호출 할 수 있습니다.
생성자가 매개 변수를 허용하면 모든 매개 변수를 전달할 수 있습니다.
등록된 댓글이 없습니다.