Javascript
Javascript) 화살표 함수와 일반 함수의 차이
choogro
2022. 8. 16. 18:27
화살표 함수는 function 키워드 대신 화살표(=>)를 사용하여 기존의 함수 정의 방식보다 간략하게 함수를 정의할 수 있다.
그러나 정의 방식 말고도 일반 함수와 차이 나는 게 많은데 그것들에 대해서 알아보도록 하자.
1. 화살표 함수는 인스턴스를 생성할 수 없는 non-constructor다.
non-constructor 란 말은 생성자 함수로서 호출할 수 없다는 말이다. 이는 곧 인스턴스를 생성할 수 없음을 의미한다.
function Func() {
console.log("hello");
}
new Func(); // hello
const Fun = () => {
console.log("Hi");
};
new Fun(); // TypeError: Fun is not a constructor
2. 중복된 매개변수 이름을 선언할 수 없다.
function Func(a, a) {}
const Fun = (a, a) => {}; // SyntaxError: Duplicate parameter name not allowed in this context
3. this가 가리키는 대상
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
return arr.map(function (item) {
return this.prefix + item;
});
}
}
const prefixer = new Prefixer("choo");
prefixer.add(["heon", "woo"]); // TypeError: Cannot read properties of undefined (reading 'prefix')
클래스 내부의 모든 코드에는 strict mode가 암묵적으로 적용된다.
따라서 콜백함수에도 strict mode가 적용된다.
strict mode에서 일반 함수로서 호출된 모든 함수 내부의 this에는 전역 객체가 아니라 undefined가 바인딩된다.
위 코드에서는 콜백 함수의 this와 외부 함수의 this가 서로 다른 값을 가리키고 있기 때문에 에러가 발생한다.
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
console.log(this); // Prefixer { prefix: 'choo' }
}
add(arr) {
return arr.map(function (item) {
console.log(this); // undefined
});
}
}
const prefixer = new Prefixer("choo");
prefixer.add(["heonwoo"]);
ES6에서는 화살표 함수를 사용하여 콜백 함수 내부의 this 문제를 해결할 수 있다.
class Prefixer {
constructor(prefix) {
this.prefix = prefix;
}
add(arr) {
return arr.map((item) => this.prefix + item);
}
}
const prefixer = new Prefixer("choo");
console.log(prefixer.add(["heon", "woo"])); // [ 'chooheon', 'choowoo' ]
화살표 함수는 함수 자체의 this 바인딩을 갖지 않는다.
화살표 함수 내부에서 this를 참조하면 상위 스코프의 this를 그대로 참조한다.
따라서 this는 함수가 정의된 위치에 의해 결정된다는 것을 의미한다.
// 화살표 함수의 this는 상위스코프인 즉시 실행 함수의 this를 가리킨다.
(function () {
const foo = () => console.log(this);
foo();
}.call({ a: 1 })); // { a: 1 }
// 상위스코프는 전역이므로 this는 전역 객체를 가리킨다.
const foo = () => console.log(this);
foo(); // window
메서드를 화살표 함수로 정의하는 것은 피해야 한다.
// Bad
const person = {
name: "choo",
sayHi: () => console.log(`Hi ${this.name}`),
};
person.sayHi(); // Hi undefined
// Good
const person = {
name: "choo",
sayHi() {
console.log(`Hi ${this.name}`);
},
};
person.sayHi(); // Hi choo
<참고자료>
http://www.kyobobook.co.kr/product/detailViewKor.laf?mallGb=KOR&ejkGb=KOR&barcode=9791158392239
모던 자바스크립트 Deep Dive - 교보문고
자바스크립트의 기본 개념과 동작 원리 | 웹페이지의 단순한 보조 기능을 처리하기 위한 제한적인 용도로 태어난 자바스크립트는 과도하다고 느껴질 만큼 친절한 프로그래밍 언어입니다. 이러
www.kyobobook.co.kr