화살표 함수로 표현하기
const elements = ['Hydrogen', 'Helium','Lithium','Beryllium'];
const res1 = elements.map(function(el){
return el.length;
});
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;
});
const res1 = elements.map(el=>el.length);
화살표 함수의 특징
- 화살표 함수는 자신의 arguments 객체가 없지만, 나머지 매개변수(rest syntax)를 활용할 수 있다.
function foo(n){
const f = () => arguments[0]+n;
return f();
}
foo(1);
function foo(n){
const f = (...args) => args[0]+n;
return f(2);
}
foo(1);
- 화살표 함수는 자신의 this를 가지고 있지 않으므로 메소드로 사용될 수 없다
const obj = {
i: 10,
b: ()=>console.log(this.i, this);
c: function(){
console.log(this.i, this);
}
}
obj.b();
obj.c();
- 화살표 함수는 생성자로서 사용될 수 없으며 new와 함께 사용하면 오류가 발생한다
const Boo = function(){
console.log('hello');
};
const boo = new Boo();
const Foo = ()=>{
console.log('hello');
};
const foo = new Foo();