Arrow Function and this keyword

운명애·2021년 2월 10일
0

JS

목록 보기
3/4

Arrow Function

Arrow functions don't bind their own 'this' keyword, which means we do not have access to this as a reference to the object where the arrow function was declared.

Inside an arrow function, this...refer(s) to the values of this in the environment the arrow function is defined in.

const event = {
	name = "Birthday Party"
  	printNameOfEvent = function () {
      console.log(this.name)
    }

위 상황에서 function 을 arrow function 으로 대체하면 undefined 값이 찍힘 따라서 this keyword 를 활용하는 method 를 object 에 만들고 싶다면 일반적인 함수의 형태로 써야하지만 ES6 부터 아래처럼 더 간결한 syntax 로 쓸 수도 있게됨.

const event = {
	name = "Birthday Party"
  	printNameOfEvent() {
      console.log(this.name)
    }

위 방법은 arrow function 은 아님. 구별!

this

const event = {
	name = "Birthday Party",
  	guestList = ['A', 'B', 'C']
  	printNameOfEvent() {
      console.log(this.name)
    },
    printNameOfGuests() {
      this.guestList.forEach(function(guest) {
        console.log(`${guest} is attending ${this.name}`)
        )
      }
                             }
event.printnameOfGuests()
// A is attendingd undefiend... 이런식으로 뜬다

한 함수를 선언하면 해당 함수 범위안에서 this 는 함수가 선언된 immediate context 를 가리킨다. global 에서 함수를 선언하면 해당 함수 범위의 this 는 global context, 브라우저 콘솔에서는 window, node 콘솔에서는 빈 object 를 반환한다. 한 object 안에서 method 로 함수가 선언된다면, this 는 해당 object 를 가리킨다.

그런데 위처럼 object 안에 method 로 선언된 함수 안에서 또 다른 함수가 선언되고 method 함수 범위 안에서 호출(call) 되면 (여기에서는 익명 함수가 선언되고 실행됨) 해당 함수, method 안에서 선언된 함수의 immediate context 는 global 로 바뀐다.

global 에서 const name = "some" 으로 선언해주면, event.printNameOfGuests( ) 를 실행했을 때 A is attending some 과 같은 값이 계속 찍힐 것이다.

이를 해결하는 한 방법은 method 안의 함수를 arrow function 으로 선언하는 것이다. arrow function 은 자체적으로 this context 를 가지지 않기 때문에 this 는 자신이 선언된 범위의 함수 this 와 동일한 것을 가리킨다.

const event = {
	name = "Birthday Party",
  	guestList = ['A', 'B', 'C']
  	printNameOfEvent() {
      console.log(this.name)
    },
    printNameOfGuests() {
      this.guestList.forEach((guest) => {
        console.log(`${guest} is attending ${this.name}`)
        )
      }
    }
event.printNameofGuests()
// A is attending Birthday Party
// ...
                    
profile
개발자 하고 싶어요..

0개의 댓글