Front-End/JavaScript

[JavaScript] 화살표 함수

LightSource 2022. 5. 20. 16:47

화살표 함수

// 매개변수 지정 방법
    () => { ... } // 매개변수가 없을 경우
     x => { ... } // 매개변수가 한 개인 경우, 소괄호를 생략할 수 있다.
(x, y) => { ... } // 매개변수가 여러 개인 경우, 소괄호를 생략할 수 없다.

// 함수 몸체 지정 방법
x => { return x * x }  // single line block
x => x * x             // 함수 몸체가 한줄의 구문이라면 중괄호를 생략할 수 있으며 암묵적으로 return된다. 위 표현과 동일하다.

() => { return { a: 1 }; }
() => ({ a: 1 })  // 위 표현과 동일하다. 객체 반환시 소괄호를 사용한다.

() => {           // multi line block.
  const x = 10;
  return x * x;
};

화살표함수에서의 array-like

  • array-like객체는 중괄호를 사용하므로 화살표 함수의 중괄호 생략과 혼동 될 수 있어서 소괄호로 구분지어서 사용한다.
function a(){ 
    return {abc:10};
}
const b=function(){return {abc:20};}
const c=()=>({abc:30});              // array-like객체는 중괄호를 사용하므로 중괄호 생략과 혼동 될 수 있어서 소괄호로 구분지어서 사용한다.
console.log(a().abc);
console.log(b().abc);
console.log(c().abc);

화살표 함수의 호출

  • 화살표 함수는 익명함수로만 사용할 수 있다.
  • 화살표 함수를 호출하기 위해서는 함수 표현식을 사용한다.
var pow = function (x) { return x * x; };
console.log(pow(10)); // 100
const pow = x => x * x;
console.log(pow(10)); // 100
  • 콜백함수로 사용하는 방법
// ES5
var arr = [1, 2, 3];
var pow = arr.map(function (x) { // x는 요소값
  return x * x;
});

console.log(pow); // [ 1, 4, 9 ]
// ES6
const arr = [1, 2, 3];
const pow = arr.map(x => x * x);

console.log(pow); // [ 1, 4, 9

화살표 함수의 this

  • 일반함수는 호출 위치에 따라 this가 정의 된다.
  • 화살표 함수는 자신이 선언된 함수 범위에서 this가 정의 된다.

일반함수

const timer={
    name:'ABC',
    timeout:function(){
        setTimeout(function(){
            console.log("name:", this.name) // name출력되지 않음
        },2000)
    }
}
timer.timeout()
  • 코드에서 timeout() 함수의 콜백함수에서의 this.name이 가리키는 것은 콜백함수의 this라서 name이 출력되지 않을 것 이다.

화살표 함수

const timer={
    name:'ABC',
    timeout:function(){
        setTimeout(()=>{
            console.log("name:", this.name) // name: ABC 출력됨
        },2000)
    }
}
timer.timeout()
  • 화살표 함수는 선언된 함수 범위에서 this를 정의하기 때문에 timer안에서 this를 찾는다.

function의 생략

const a={
    b:function(){return 1;},
    c:function(){return 2;}
}
console.log(a.b());
console.log(a.c());

위와 같은 코드를 다음과 같이 생략 할 수 있다.

const a={
    b(){return 1;},
    c(){return 2;}
}
console.log(a.b());
console.log(a.c());

키값과 밸류값이 동일한 경우의 생략

const a=10;
const b=20;
const c={a:a, b:b}; // 변수 c.a와 c.b의 키값, 밸류값의 이름이 동일함
console.log(c.a);
console.log(c.b);
const a=10;
const b=20;
const c={a, b};   // 변수 c.a와 c.b의 키값, 밸류값의 이름이 동일하므로 생략
console.log(c.a);
console.log(c.b);
반응형