Arrow function
Arrow Function
화살표 함수[ => ]는 전통적인 함수의 간편한 대안 입니다.
하지만 화살표 함수에는 몇 가지 제안이 있고 모든 상황에서 사용할 수 없습니다.
- this나 super에 대한 바인딩이 없고, methods 로 사용될 수 없습니다.
- new.target키워드가 없습니다.
- 일반적으로 스코프를 지정할 때 사용하는 call, apply, bind methods를 이용할 수 없습니다.
- 생성자(Constructor)로 사용할 수 없습니다.
- yield를 화살표 함수 내부에서 사용할 수 없습니다.
// 일반 함수
var foo = function () { console.log("abc") }; // abc
// 화살표 함수
var bar = () => console.log("kfc"); // kfc
1. 기본 문법
[매개 변수가 없는 경우]
//이름이 없는 함수
function() {}
() => {}
//이름이 있는 함수
function getName() {}
const getName() => {}
//매개변수가 하나인 경우
const getName = function(name) {}
const getName = (name) => {}
//매개변수가 한개인 경우 ()생략이 가능하다.
const getName = name => {}
//매개변수가 여러개인 경우
const getName = function(name, age) {}
const getName = (name, age) => {}
//return
function hi(text) {
text += '하세요';
return text;
}
const hi = text => {
text += '하세요';
return text
};
//만약 함수가 실행내용이 딱히 없이 return만 한다면 키워드와 중괄호가 생략가능하다.
function getName(name) {
return name;
}
const hi = name => { return name };
//생략
const hi = name => name;
//return이 없는 경우
const hi = (name, age) => {name+age}; //return이 없을 때 {}를 사용
//객체를 반환할 때
const hi = () => ({a:1,b:2,c:3});
//callback 함수
const number = [1,4,9];
const oddArr = number.filter(function(x) {return x%2 !== 0;});
console.log(oddArr); //[1.9]
const number = [1,4,9];
const oddArr = number.filter(x => (x%2) !== 0);
console.log(oddArr); //[1.9]
2. this
//function
function Person() {
// Person() 생성자는 `this`를 자신의 인스턴스로 정의.
this.age = 0;
console.log(this.age) //0
setInterval(function growUp() {
// 비엄격 모드에서, growUp() 함수는 `this`를
// 전역 객체로 정의하고, 이는 Person() 생성자에
// 정의된 `this`와 다름.
this.age++;
console.log(this.age) //NaN
}, 1000);
}
const p = new Person();
//arrow function
function Person(){
this.age = 0;
console.log(this.age); //0
setInterval(() => {
this.age++; // |this|는 Person 객체를 참조
console.log(this.age); //2,3,4,5
}, 1000);
}
const p = new Person();
- arrow function은 외부에 있던 this를 그대로 내부로 가져와서 사용하는 함수이다.
- 내가 예측한 this값과 달라질 수 있으니 단점이 될 수 있다.
댓글남기기