📚 프론트엔드 공부 일지/REACT

constructor / super

wei3on 2024. 7. 18. 14:00

 

constructor(생성자)

contructor(생성자)를 이용하면 인스턴스화된 객체에서 다른 메서드를 호출하기 전에

수행해야하는 사용자 지정 초기화를 제공할 수 있음

 

class User {
	construnctor(name) {
    	this.name = name
    }
    sayHi() {
    	alert(this.name)
    }
}

let user = new User("John")
user.sayHi()

클래스를 new를 붙여서 ( new User("John") ) 인스턴스객체로 생성하면

넘겨받은 인수와 함께 construnctor가 먼저 실행됨

이 때, 넘겨받은 인수인 John이 this.name에 할당됨

 

super

 

super 키워드는 자식 클래스 내에서 부모 클래스의 생성자 or 메소드를 호출할 때 사용됨

class Car {
	construnctor(brand) {
    	this.carname = brand
    }
    present() {
    	return 'I have a' + this.carname
    }
}

class Model extends Car {
	construnctor(brand, mod) {
    	super(brand)
        this.model = mod
    }
    show() {
    	return super.present() + ', it is a' + this.model
    }
}

let mycar = new Model("Ford", "Mustang")
mycar.show()

 

super(brand) -> 자식 클래스 내에서 부모 클래스의 생성자 호출

super.present() -> 자식 클래스 내에서 부모 클래스의 메소드를 호출

 

super 이후에 this 키워드

생성자에선 super 키워드 하나만 사용되거나 this 키워드가 사용되기 전에 호출

 

이유는

1. 부모 클래스의 생성자를 호출하기 전에 this.를 사용하려고 하면 문제가 됨

2. React에서 this.state를 생성자에서 정의할 떄 super가 먼저 와야 하는 이유도 이와 같음

'📚 프론트엔드 공부 일지 > REACT' 카테고리의 다른 글

React 확장 프로그램 / Profiler 성능 측정 프로그램  (6) 2024.07.24
React Hooks  (0) 2024.07.19
filter / real state  (0) 2024.07.18
Props / Key  (0) 2024.07.10
React Icon  (0) 2024.07.09