화살표함수를 좀더 알아보려고 한다.
먼저 함수를 생성하는 방법은 아래의 3가지가 있다.
//함수 선언식
function hello(name) {
console.log(`Hello, ${name}!!`)
}
//함수실행
hello('hinyc')
// > Hello, hinyc!!
//함수 표현식
//익명함수를 변수에 할당하는 방식
const hello = function (name) {
console.log(`Hello, ${name}!!`)
}
//함수실행
hello('hinyc')
// > Hello, hinyc!!
// 함수표현식의 간편한 대안
const hello = (name) => {
console.log(`Hello, ${name}!!`)
}
//함수실행
hello('hinyc')
// > Hello, hinyc!!
예로 살펴 보자 MDN예제 참고.
const array = ['Apple', 'Tiger', 'LemonTree'];
//화살표 함수 기본 형태
const arrayLengths1 = array.map((el) => {
return el.length;
});
// 화살표함수의 유일한 문장이 return일때 {}와, return을 생략할 수 있다.
const arrayLengths2 = array.map((el) => el.length);
**만일 반환하는것이 객체일경우 소괄호를 사용후 객체 리터럴을 사용해야한다. ()=> ({});
// 파라미터가 하나일경우 ()를 생략할 수 있다.
const arrayLengths3 = array.map(el => el.length);
// 구조분해(destructuring)를 사용하여 해당 속성만 새로운 변수로 지정해서 사용할 수 있음.
const arrayLengths4 = array.map(({ length: arrayLength }) => arrayLength);
// 구조분해(destructuring)를 사용하여 해당 속성을 그대로 사용할 수 있음.
const arrayLengths5 = array.map(({ length }) => length);
//
//arrayLengths1~5는 모두 같은 배열을 같는다. > [5, 5, 9]
함수를 사용할때 가금 함수내에서 변수를 선언하거나 재할당 하는 경우가 종종있다.
//느슨한 모드
const fruits1 = (anyThing) => {
fruit = `${anyThing} good`; // 앞서 선언된 변수가 없기때문에 전역변수로 할당된다.
return `${anyThing}!!`;
};
console.log(fruits1('apple')); // > apple!!
console.log(fruit); // > apple, 전역변수이기 때문에 어디서든 변수를 가저올수 있다.
//엄격 모드
const fruits2 = (anyThing) => {
'use strict'; // 함수의 첫문장으로 'use strict', "use strict"를 넣어주면 엄격모드 실행.
fruit2 = `${anyThing} good`;
return `${fruit2}!!`;
};
console.log(fruits2('apple')); // > fruit2라는 변수가 선언된적이 없기 때문에 에러발생 : Uncaught ReferenceError: fruit2 is not defined
- this나 super(아직 학습하지않은 부분)에 대한 바인딩이 없고, methods 로 사용될 수 없습니다.
- new.target키워드가 없습니다(학습하지않음).
- 일반적으로 스코프를 지정할 때 사용하는 call, apply, bind methods를 이용할 수 없습니다(학습하지않음).
- 생성자(Constructor)로 사용할 수 없습니다(학습하지않음).
- yield를 화살표 함수 내부에서 사용할 수 없습니다(학습하지않음).
지금은 모르는부분이 대부분이라 모두 이해하지 못하지만 일단 this의 차이부터 공부해보려고 한다.