[낙서 #15] 2022년 2월 28일

낙서·2022년 2월 28일
0

낙서

목록 보기
15/22

늘 헷갈려버리는 일반함수화살표함수의 차이, this가 차이가 있다

  • 일반함수 안에서 사용된 this는 자신이 종속된 **객체**를 가리킨다
  • 화살표함수 안에서 사용된 this는 자신이 속한 객체가 아닌 자신이 종속된 **인스턴스**를 가리킨다

일반함수

function Person () {
	this.name = '홍길동';
    
   	return {
    	name: '스폰지밥',
        printName: function () {
          console.log(this.name);	// 결과: 스폰지밥, this가 자신이 종속된 객체 가리킴
        }
    };
}

화살표함수

function Person () {
	this.name = '홍길동';
    
   	return {
    	name: '스폰지밥',
        printName: () => {
          console.log(this.name);	// 결과: 홍길동, this가 자신이 종속된 Person 인스턴스 가리킴
        }
    };
}

늘 헷갈려버리는 함수 표현식, 함수 선언식

함수 선언식

function () {...}

함수 표현식

const fn = () => {...}

표현해서 변수에 할당해버린다.

클래스가 아닌 함수 컴포넌트 사용 이유

빌드했을 때 파일 크기가 더 작다. 클래스를 구성하는 요소들이 빠지기 때문

inline style useState 값으로 할당 할 때

jsx 요소의 inline style을 key: value 형태로 넘겨주는 것이 아닌, state 이름을 style 속성 key와 같게 선언하면 이렇게 함축하여 표현 전달 가능

import { useState } from 'react';

const MyComponent = () => {
	const [color, setColor] = useState('blue');
  	const [backgroundColor, setBackgroundColor] = useState('yellow');
  	const [fontWeight, setFontWeight] = useState(800);
  
  	return (
    	<div style={{ color, backgroundColor, fontWeight }}>My Component</div>
    );
};

export default MyComponent;
profile
Deprecated

0개의 댓글