시작 하기 앞서, 이 글을 참고 했음을 밝힙니다.
https://www.freecodecamp.org/news/the-difference-between-arrow-functions-and-normal-functions/
자바스크립트에는 두 가지의 함수가 있다
- Normal Function
- Arrow Function
Arrow Function은 ES6 에서 제공되었습니다.
Normal Function example
function multiply(num1, num2) {
const result = num1 * num2
return result
}
Arrow Function Example
const multiply = (num1, num2) => {
const result = num1 * num2
return result
}
1. arrow function에서는 arguments 객체가 없다
function print() {
console.log(arguments)
}
print("hello", 400, false)
// {
// '0': 'hello',
// '1': 400,
// '2': false
// }
-----------
const print = () => {
console.log(arguments)
}
print("hello", 400, false)
// Uncaught ReferenceError: arguments is not defined
2. Arrow function은 this binding을 자체적으로 만들지 않는다
const obj = {
name: 'deeecode',
age: 200,
print: function() {
console.log(this)
}
}
obj.print()
// {
// name: 'deeecode',
// age: 200,
// print: [Function: print]
// }
-------
const obj = {
name: 'deeecode',
age: 200,
print: function() {
function print2() {
console.log(this)
}
print2()
}
}
obj.print()
// Window
// print2 는 어떤 객체에서도 불리지 않으므로 this가 Window 객체를 나타낸다
------
const obj = {
name: 'deeecode',
age: 200,
print: () => {
console.log(this)
}
}
obj.print()
// Window
// arrow 함수에서 자동으로 this binding을 하지 않으므로 자연스럽게 this는 Window를 가리킨다
-----
const obj = {
name: 'deeecode',
age: 200,
print: function() {
const print2 = () => {
console.log(this)
}
print2()
}
}
obj.print()
// {
// name: 'deeecode',
// age: 200,
// print: [Function: print]
// }
// 위의 arrow function인 print2는 obj의 print 내부에 선언되어 있다.
// obj.print는 일반 함수 이므로 this 바인딩이 자동으로 되어 this는 obj를 가리킨다.
// print2의 this는 결국 print의 this로 된다.
3. arrow function은 생성자로 사용 될 수 없다
2번 화두에서 arrow function은 this를 바인딩하지 않는다고 하였습니다.
따라서 그러한 이유로 class에서 생성자로 사용 될 수 없습니다.
예제 코드
class Animal {
constructor = (name, numOfLegs) => {
this.name = name
this.numOfLegs = numOfLegs
}
sayName() {
console.log(`My name is ${this.name}`)
}
}
// Uncaught SyntaxError: Classes may not have a field named 'constructor'
위의 코드에서 constructor는 생성자가 아닌, 클래스 객체내의 메서드 함수로써 선언됩니다.
따라서 이미 지정된 예약어인 constructor를 override 할 수 없습니다.
4. arrow function은 선언 될 수 없다
function printHello() {
console.log("hello")
}
위 예제는 선언된 함수입니다. (declared function)
const printHello = function() {
console.log("hello")
}
위 예제는 함수 표현입니다. (function expression)
const printHello = () => {
console.log("hello")
}
위 예제는 함수 선언이 아닙니다.
printHello는 function expression으로 할당된 변수 입니다.
5. arrow function은 초기화 되기 전에 접근할 수 없다
printName()
console.log("hello")
function printName() {
console.log("i am dillion")
}
// i am dillion
// hello
------
printName()
console.log("hello")
const printName = () => {
console.log("i am dillion")
}
// ReferenceError: Cannot access 'printName' before initialization
← Go home