Script/ㄴ ES6 신문법

[ES6] this 와 arrow function에 대해

hhnn 2022. 6. 14. 12:17

 

 

See the Pen 개인study by limhaneul2244 (@limhaneul2244) on CodePen.

 

1. 간단한 메소드 만들기

let person = {
  name: 'nana',
  sayHi: function(){
    console.log(`안녕 나는 ${this.name}`)
  }
}

person.sayHi(); //안녕 나는 nana

 

2. 오브젝트 내의 데이터를 전부 더해주는 메소드만들기

let 자료 = {
  data : [1,2,3,4,5]
};

자료.전부더하기 = function () {
  let total = 0;
  this.data.forEach(function(a){
    total = a + total;
  });
  console.log(total)
}
자료.전부더하기()

여기서 자료의 object를 arrow function으로 변경하면 에러가 난다.

그 이유는 arrow function은 어디서 쓰든간에 내부의 this 값을 변화 시키지 않기 때문이다.

arrow function 을 사용하려면 this를 자료로 바꿔주어야 한다.

arrow function 의 장점
어디서 쓰든간에 내부의 this 값을 변화 시키지 않는다.
바깥에 있던 this의 의미를 그대로 내부에서도 사용하는 함수

 

반응형
SMALL