이챙의 개발 log
화살표 함수(arrowFunction)와 일반함수(function)의 차이점 알아보기
자바스크립트에서 일반함수와 화살표함수 두가지의 함수가 있다. 이 두 함수는 기능이 다르다. 차이점을 알아보자
⭐1. this
1) 일반함수
- 일반적으로 함수를 호출할 경우 global 객체를 가리킨다(기본적으로 window 객체)
function func1() {
console.log(this);
}
func1(); // window object
- 메소드함수를 호출할 경우 메소드를 소유한 객체를 가리킨다
const obj = {
name:'공작새',
method() {
console.log(this.name); // 공작새
}
};
this가 obj객체 이기때문에 method() 호출시 obj.name의 값이 콘솔에 찍힌다
- 생성자를 호출할 경우 새 인스턴스를 가리킨다
function funcFactory() {
console.log(this);
}
new funcFactory(); // funcFactory
2) 화살표함수
화살표 함수 내에서 자체적으로 가리키는 this가 없다.
상위 스코프의 this를 가리킨다.
let myObj = {
age: 30,
arrowFunc:() => {
console.log(this.age);
},
regularFunc(){
console.log(this.age);
}
};
myObj.arrowFunc(); //undefined
myObj.regularFun(); //30
myObj의 객체 내에 화살표 함수로 메소드를 정의 한 후 this.age 속성을 불러오면? 화살표 함수의 this를 모른다면 기대하는 값은 30이지만 결과는 undefined 이다. 화살표함수의 상위 스코프는 현재 myObj 객체가 아니라 상위스코프인 window 객체이기 때문이다
일반함수 메소드 안에서 this를 저장하기 위해 var self = this 요런 변수들을 많이 사용했었는데 화살표 함수를 쓰면 이런 방법을 사용 할 필요가 없다
또한 화살표 함수내에서 bind,call,apply를 사용하여 this바인딩을 할 수 없다.
⭐2. Arguments
- 일반함수에서는 arguments의 사용이 가능하다
function regularFunc() {
console.log(arguments,arguments[0]); //[1,2,3],1
}
regularFunc(1,2,3)
- 화살표함수에서 사용할 경우 에러가 난다
const arrFunc = () => {
console.log(arguments,arguments[0]); //arguments is not defined
}
arrFunc(1,2,3)
🙆♀️화살표 함수에서 rest 파라미터를 사용하면 arguments 사용이 가능하다
const arrFunc = (...args) => {
console.log(...args); //[1,2,3]
}
arrFunc(1,2,3)
⭐3. 생성자함수 사용
일반함수에선 생성자 함수 사용이 가능하다.
function Cfunc(){
this.age = 20
}
const a = new Cfunc()
console.log(a.age)// 20
화살표함수에선 생성자 함수 사용이 안된다.
const CarrowFunc = () => {
this.age = 20
}
const a = new CarrowFunc() // CarrowFunc is not a constructor
=> 화살표함수 내의 this가 렉시컬 스코프로 사용되기 때문에 생성자 함수내의 this로 사용이 불가능 한것
📢가장 큰 차이점은 this 인거 같다.
일반함수는 동적으로 this가 결정되지만 화살표함수는 정적으로 this가 결정되기 때문에 이벤트 호출시나 콜백함수를 사용 할 경우 this를 어떻게 사용하냐의 따라 그에 맞는 함수를 사용 할 수 있을 거 같다.
출처:https://hhyemi.github.io/2021/06/09/arrow.html
JavaScript - 화살표 함수와 일반 함수의 차이 - CODE:H
화살표 함수(Arrow Function)란 화살표함수는 ES6에서 새로 추가된 내용이다. 기존 함수 표현식과 비교하면 간결한표현으로 간단하게 사용가능하다. function fun() { // 일반함수 ... } const arrFun = () => { //
hhyemi.github.io
출처:https://blog.bitsrc.io/arrow-functions-vs-regular-functions-in-javascript-458ccd863bc1
Arrow Functions vs. Regular Functions in JavaScript
Learn when and when not to use the arrow function
blog.bitsrc.io
'javascript > es6' 카테고리의 다른 글
[es6] Symbol 이란 ..? 자세히 알아보자 (0) | 2021.03.21 |
---|---|
TDZ(Temporal Dead Zone) 란..? TDZ로 인한 var,let,const 알아보기 (0) | 2020.12.11 |
[es6]Set(),WeakSet(),set 메소드,set 으로 중복없는 배열 만들기, set 배열로 만들기 (0) | 2020.08.20 |
[es6] Destructuring assignment 구조분해할당 (0) | 2020.08.12 |
[es6]특정 문자열로 시작하는지 끝나는지 알 수 있는 메서드 startsWith() , endsWith() (0) | 2020.07.31 |
이챙(leechaeng)
프론트엔드 개발도 하고 뛰기도 하고