super(props) 란?

Dev_Go·2023년 9월 25일
0

React basic

목록 보기
12/12
post-thumbnail
constructor(name) {
    this.name = name;
}
sayHi() {
	alert(this.name);
}

let user = new User("john");
user.sayHi();

constructor

constructor(생성자)를 사용하면 인스턴트화된 객체에서 다른 메서드를 호출하기 전에 수행해야 하는 지정 초기화를 제공할 수 있습니다.

클래스를 new를 붙여서 (new User("John")) 인스턴트 객체로 생성하면 넘겨받은 인수와 함께 constructor가 먼저 샐행됩니다.
이 때 넘겨받은 인수의 John이 this.name에 할당됩니다.

자바스크립트에서 supr

  • super 키워드는 자식 클래스 내에서 부모 클래스의 생성자를 호출할 때 사용됩니다.
  • super 키워드는 자식 클래스 내에서 부모 클래스의 메소드를 호출할 때 사용됩니다.
class Car {
	constructor(brand) {
    	this.carname = beand;
    }
}

class Model extends Car {
	constructor(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 이후에 this키워드

  • 생성자에서는 super 키워드 하나만 사용되거나 this 키워드가 사용되기 전에 호출되어야 합니다.
class Component {
	constructor(props) {
		this.props = props;
      // ...
    }
}

class Square exrends React.Component {
	constructor(props) {
      	// can't use `this` yet 
    	super(props);
      	// now it's okay though
    	this.state = { a: true };
    }
  // ...
}

super 이후에 this키워드가 나와야 하는 이유

  • 아래 소스 코드에서 처럼 부모 클래스의 생성자를 호출하기 전에 this.name을 사용하려고 하면 문제가 되기 때문
  • React에서 this.state를 생성자에서 정의할 때 super가 먼저와야 하는 이유도 이와 같습니다.
class Person {
	constructor(name) {
		this.name = name;
    }
}
class PolitePerson exrends Person {
	constructor(name) {
      	// this가 위에 있어서 오류코드
      	this.greetColleagues();
    	super(name);
    }
  greetColleagues() {
  	alert('My name is' + this.name + ', nice to meet you!');
  }
}

React에서 super에 props를 인자로 전달하는 이유

  • React.Component 객체가 생성될 때 props 속성을 초기화하기 위해 부모 컴포넌트에서 props를 전달
  • 생성자 내부에서도 this.props를 정상적으로 사용할 수 있도록 보장하기 위해서.
// Inside React
class Component {
	constructor(props) {
		this.props = props;
      // ...
    }
}

// Inside your code
class Button extends React.Component {
	constructor(props) {
    	super(); // we forgot to pass props
      	console.log(props); // ok {}
      	console.log(this.props); //undefined
    }
  // ...
}

class Button extends React.Component {
	constructor(props) {
    	super(props);
      	console.log(props); // ok {}
      	console.log(this.props); // ok {}
    }
  // ...
}
profile
프론트엔드 4년차

0개의 댓글