화살표 함수

Creating the dots·2021년 9월 4일
0

Javascript

목록 보기
23/24

화살표 함수로 표현하기

const elements = ['Hydrogen', 'Helium','Lithium','Beryllium'];

//function 표현
const res1 = elements.map(function(el){
  return el.length;
}); 

//arrow function
const res1 = elements.map((el)=>{
  return el.length;
});

//파라미터가 하나만 있을 경우 주변 괄호를 생략할 수 있다.
const res1 = elements.map(el=>{
  return el.length;
});;

//파라미터가 두개이상인 경우 주변 괄호를 작성해줘야 한다.
const res2 = elements.map((el,idx)=>{
  return el.length+idx;
});

//화살표 함수의 유일한 문장이 'return'일때 'return'과 중괄호{}는 생략할 수 있다
const res1 = elements.map(el=>el.length);

화살표 함수의 특징

  • 화살표 함수는 자신의 arguments 객체가 없지만, 나머지 매개변수(rest syntax)를 활용할 수 있다.
function foo(n){
  const f = () => arguments[0]+n; //화살표 함수는 자신의 arguments가 없으므로 여기서 arguments[0] = n
  return f();
}
foo(1); //따라서 foo(n)은 n+n의 값을 갖는다

function foo(n){
  const f = (...args) => args[0]+n; 
  return f(2);//rest parameter로 만들어진 args[0] = 2이다
}
foo(1); //따라서 foo(n)은 2+n의 값을 갖는다
  • 화살표 함수는 자신의 this를 가지고 있지 않으므로 메소드로 사용될 수 없다
const obj = {
  i: 10,
  b: ()=>console.log(this.i, this);
  c: function(){
    console.log(this.i, this);
  }
}
obj.b(); //undefined, Window {...} (or the global object)
obj.c(); //10, {i: 10, b: ƒ, c: ƒ}
  • 화살표 함수는 생성자로서 사용될 수 없으며 new와 함께 사용하면 오류가 발생한다
//function 함수를 new와 함께 사용했을때
const Boo = function(){
  console.log('hello');
};
const boo = new Boo(); //hello

//화살표 함수를 new와 함께 사용했을때
const Foo = ()=>{
  console.log('hello');
};
const foo = new Foo(); //Uncaught TypeError: Foo is not a constructor
profile
어제보다 나은 오늘을 만드는 중

0개의 댓글