늘 헷갈려버리는 일반함수
와 화살표함수
의 차이, 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 = () => {...}
표현해서 변수에 할당해버린다.
빌드했을 때 파일 크기가 더 작다. 클래스를 구성하는 요소들이 빠지기 때문
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;