231011 개발일지 TIL - JavaScript에서 화살표 함수는 this를 바인딩하지 않는다.

The Web On Everything·2023년 10월 11일
0

개발일지

목록 보기
154/269

JavaScript에서 화살표 함수는 this를 바인딩하지 않는다.

일반적인 함수와 화살표 함수의 가장 큰 차이점 중 하나는 this 키워드를 다루는 방식이다. 일반적인 함수에서 this는 호출하는 객체에 바인딩되는 반면에 화살표 함수에서 this는 자신을 포함하는 외부 범위의 컨텍스트에 바인딩된다.

const person = {
	name: 'john',
	age: 31,
	isMarried: true,
	sayHello: function() {
		console.log(`hello, my name is ${this.name}`);
	},
}

person.sayHello(); // "hello, my name is john"

위 코드에서 sayHello 메서드는 일반적인 함수로 정의되었으며, 이 경우 this는 호출한 객체 즉 person을 가리킨다.

const person = {
	name: 'john',
	age: 31,
	isMarried: true,
	sayHello: () => {
		console.log(`hello, my name is ${this.name}`);
	},
}

person.sayHello(); // "hello, my name is undefined"

그러나 위와 같이 화살표 함수로 정의하면 sayHello 메서드 내부의 this는 외부 범위(즉 전역 범위)에 바인딩되므로 이름이 정의되지 않았기 때문에 결과가 undefined가 출력된다.

profile
오늘은 무슨 오류를 만날까?! 널 만나러 가는 길~ LOL

0개의 댓글