본문 바로가기
카테고리 없음

JavaScript - arrow function (ES6)

JavaScript ES6 에서 나온 arrow function 에 대해서 알아보겠습니다.

 

#표현식

 

// 인수가 없을 때
const test1 = () => {};

// 인수가 하나 일 때
const test2 = (a) => {};

// 인수가 복수 일 때
const test3 = (a, b) => {};

// {} 블럭을 사용하지 않았을 때
const test4 = (a, b) => a + b;
const test5 = (a, b) => (result = a + b);

여기서 주의 해야 할 것은 {} 안에 어떠한 처리를 한 후에, 특정 값을 받고 싶다면 return 을 써줘야 합니다.

() 안에 있는 처리는 자동으로 arrow function 이 리턴을 해주게 됩니다.

 

그 예시는 아래와 같습니다.

let a = 1;
let b = 1;
let result = 0;

const test4 = (a, b) => a + b;

const test5 = (a, b) => (result = a + b);

const test6 = (a, b) => {
  result = a + b;
};

const test7 = (a, b) => {
  return (result = a + b);
};

console.log(test4(a, b)); //2

console.log(test5(a, b)); //2

console.log(test6(a, b)); //undefined

console.log(test7(a, b)); //2

 

#this

const test = {
  a: '서울시',
  b: '강남구',
  printAddress: function () {
    console.log(this);
    console.log(this.a + ' ' + this.b);
  }
};

test.printAddress(); // 서울시 강남구

 

const test2 = {
  a: '서울시',
  b: '강남구',
  printAddress: function () {
    setTimeout(function () {
      console.log(this);
      console.log(this.a + ' ' + this.b);
    }, 500);
  }
};

let address = test2.printAddress(); // undefined undefined

 

const test2 = {
  a: '서울시',
  b: '강남구',
  printAddress: function () {
    let that = this;
    setTimeout(function () {
      console.log(that);
      console.log(that.a + ' ' + that.b);
    }, 500);
  }
};

test2.printAddress(); // 서울시 강남구

 

const test2 = {
  a: '서울시',
  b: '강남구',
  printAddress: function () {
    setTimeout(
      function () {
        console.log(this.a + ' ' + this.b);
      }.bind(this),
      500
    );
  }
};

test2.printAddress();

 

함수가 호출 될 때 this 가 바인딩할 객체를 찾는 방식은 추가적으로 조사..