TIL( 20.03.24 ) javascript arrow function

이민택·2020년 3월 24일
0

TIL

목록 보기
32/44

arrow function

arrow function 은 es6에서 추가된 문법으로 함수를 정의 할 때 사용한다.

let test=()=>{
  console.log('this is arrow function');
}
test();

arrow function에는 없는 3가지

1. 함수 이름

function test(){
  console.log('this is function');
}

let test2=()=>{
  console.log('this is arrow function');
}

2. this

일반적인 함수는 자기만의 this가 존재하지만 arrow function은 자기만의 this가 없기 때문에 스코프 체인의 의해 자기 자신 외부의 this를 가져온다 이런 특징때무에 bind,call,apply로 this를 전달 할 수 없다

const btn =document.getElementById('btn');

var myObj={
  count: 3,
  setCounter : function(){
  	console.log(this.count); // 3이된다 this는 my obj
    btn.addEventListner('click',function(){
      console.log(this);     //클릭하면 버튼객체가 나온다 
    })
  }
};

myObj.setCounter(); 

위 예제에서 버튼을 누르면 버튼 객체가 this가 되기 때문에 이를 해결하기 위해 bind를 이용해서 아래와 같이 했었다.

const btn =document.getElementById('btn');

var myObj={
  count: 3,
  setCounter : function(){
  	console.log(this.count); // 3이된다 this는 my obj
    btn.addEventListner('click',function(){
      console.log(this);     //this 는 obj
    }).bind(this);
  }
};

myObj.setCounter(); 

그런데 arrow function을 사용하게 되면 bind를 사용하지 않아도 함수가 실행될 때의 동일한 this에 접근한다 this가 없기 때문에 new 연산자를 이용해서 객체를 생성할 수 도 없다

const btn =document.getElementById('btn');

var myObj={
  count: 3,
  setCounter : () => {
  	console.log(this.count); // 3이된다 this는 my obj
    btn.addEventListner('click',function(){
      console.log(this);     //this 는 obj
    });
  }
};

myObj.setCounter(); 

3. argument

arrow function 은 argument를 이용하여 여러개의 매개변수를 받아 올 수 없다 따라서 사용하기 위해서는 아래와 같이 스코프 체인을 이용하거나 전개 연산자를 (...) 사용하면 된다.

const myFun =function (){
  console.log(arguments);
}

// 스코프 체인
function outter(){
  const myFun2= () =>{
    console.log(arguments);
  }
}

outter(1,2,3,4)
//전개 연산자
const myFun2 = (...args) => {
  console.log(args)
}

arrow function을 사용하는 이유

profile
데이터에 소외된 계층을 위해 일을 하는 개발자를 꿈꾸는 학생입니다

0개의 댓글