개발Story
Published 2023. 1. 2. 17:56
[JavaScript] this Javascript/문법

javascript This의 정의

this란 javascript의 예약어다.

 

this는 함수가 호출될때 결정이 된다.

화살표 함수에서의 this는 함수가 속해잇는곳의 상위 this를 가르킨다.

 + 좀 더 디테일하게 설명하면 런타임시에 해당 객체가 존재하는 스코프가 this가 된다.

 

예제를 통해 알아보자.

1. [예제1 : this는 함수가 호출될때 결정이 된다.]

<javascript />
const car = { name: 'KIA', getName: function () { console.log('car getName', this) }, } car.getName() // car 객체 const globalCar = car.getName globalCar() // window 객체

첫번째 car.getName() car의 객체가 나오고

두번째 globalCar() window최상위 객체가 나온다.

 

car.getName()는 car라는 객체가 호출하였기 때문에 car의 객체가 출력된거고

globalCar()  window객체가 호출하였기 때문에 window객체가 출력된 것 이다.

 

즉 this는 함수가 호출될때 결정이 된다.

 

2. [예제2 : this는 bind함수를 통해 고정시킬 수 있다.]

<javascript />
const car = { name: 'KIA', getName: function () { console.log('car getName', this) }, } car.getName() const globalCar = car.getName; globalCar() const car2 = { name: 'hyundai', getName: car.getName } car2.getName() // car2객체 hyundai const bindGetname = car2.getName.bind(car) bindGetname() //car의 객체 KIA

car2.getName()은 car2의 객체 hyundai가 출력된다.

bindGetName()은 car의 객체 KIA가 출력된다.

 

bind 함수를 통해 car를 바인딩 해줬기 때문이다.(this를 고정시킬 수 있다.)

 

3. [예제3 : 객체 안에 함수도 window객체가 호출하면 window객체를 가르킨다.]

<javascript />
const testCar = { name: 'benz', getName: function () { console.log('getname', this.name) const innerFunc = function () { console.log('innerFunc', this) } innerFunc() }, } testCar.getName() //getname 은 benz , innerFunc는 window객체를 출력한다.

getName안에 있는 innerFunc()도 window객체가 호출했기 때문에 window객체를 this로 가르킨다.

 

innerFunc안에 있는 this를 getName안에 있는 this랑 같게만들려면 화살표 함수를 사용하면 된다.

 

4. [예제4 :  화살표 함수에서의 this는 함수가 속해있는곳의 상위 this를 계승 받는다.]

<javascript />
const testCar = { name: 'benz', getName: function () { console.log('getname', this.name) const innerFunc = () =>{ console.log('innerFunc', this) } innerFunc() }, } testCar.getName()

즉 화살표 함수에서의 this는 함수가 속해있는곳의 상위 this를 계승 받는다.

 

일반 함수에서의 this와 화살표 함수의 this는 다르다.

profile

개발Story

@슬래기

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!