일반 함수와 화살표 함수의 this에 대하여
const person = {
name: 'John',
sayName: function() {
console.log(`My name is ${this.name}`);
// 일반 함수 내부에서 this를 사용할 때
function innerFunction() {
console.log(`Hello, ${this.name}!`); // undefined
}
innerFunction();
// 화살표 함수 내부에서 this를 사용할 때
const arrowFunction = () => {
console.log(`Hi, ${this.name}!`); // John
}
arrowFunction();
}
}
person.sayName();
일반 함수의 this는 함수 자신을 의미하고
화살표 함수에서 this는 종속된 인스턴스(상단의 경우엔 person)을 의미합니다.
위의 코드에서 innerFunction함수에서 this.name = undefined된 것은
unnerFunctioin함수 내에서 name값을 정해주지 않았기 때문이며,
arrowFunction함수에서 this.name이 John이 된 이유는
화살표 함수에서 this는 자신이 종속된 인스턴스(person)을 뜻하기 때문입니다.
person에서 name = 'John'을 선언했기 때문에 arrowFunction의 종속된 인스턴스
즉, 부모요소를 해당하는 this가 사용되어 this.name은 John을 반환합니다.
또 다른 예시
import React, { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
// state의 초깃값 설정하기
this.state = {
number: 0
// state를 조회할 때는 this.state로 조회합니다.
};
}
render() {
const { number } = this.state;
return (
<div>
<h1>{number}</h1>
<button onClick={function(){this.setState({number: number +1})}}>
+1버튼
</button>
<button onClick={() => {this.setState({number: number +1})}}>
+1버튼
</button>
</div>
);
}
}
export default Counter;
button태그 onClick에 일반적인 함수와 화살표 함수 두가지 방식으로 함수를 만들었습니다.
this
를 지칭할 수 있는것이 없기 때문에 Error
가 출력됩니다.