aotoyae

[JS] Arrow Function 화살표 함수, 함수 표현식, this 우회 본문

JavaScript

[JS] Arrow Function 화살표 함수, 함수 표현식, this 우회

aotoyae 2024. 1. 2. 17:39

💡 함수 선언문

선언 전에 호출이 가능하다. (호이스팅) ➡️ 자유로운 위치에서 부를 수 있다.

// 함수 선언문
sayHello() // "Hello"

function sayHello(){
  console.log("Hello");
};

 

var  처럼 함수 스코프를 가진다.

함수 안에 선언된 함수는 밖에서 호출할 수 없지만,

function printHi() {
  function printHello() {
    console.log("Hello")
  }
  
  console.log("Hi");
  printHello(); // "Hello"
}

printHi(); // "Hi"
printHello(); // error

 

⬇️ 함수가 아닌 다른 코드블록에서 함수 선언을 하게 되면

전역적으로 호출이 가능해진다.

const x = 4;

if (x < 5) {
  function printHi() {
    console.log("Hi")
  }
}

{
  function printHello() {
    console.log("Hello")
  }
}

printHi(); // "Hi"
printHello(); "Hello"

 

 

💡 함수 표현식

함수 선언을 값처럼 사용하는 방식.  ➡️ 변수 스코프 활용 가능

선언 전에 호출 불가능! ➡️ 코드의 흐름을 더 쉽게 파악할 수 있다.

// 함수 표현식 ex1
const sayBye = function () {
  console.log("Bye");
};

sayBye(); // "Bye"

// 함수 표현식 ex2
const myBtn = document.querySelector("#myBtn");

myBtn.addEventListener("click", function () {
  console.log("button is clicked!");
});

 

👀 서로 다른 특성을 갖고 있으니 가급적 둘 중 하나를 선택해 
일관된 방식으로 함수를 만드는 게 좋다.

 

💡 화살표 함수

기존의 함수 선언문을 간결하게 만들어 준 문법.

익명 함수이다!

// 기본 함수
function add(x, y) {
  return x + y;
}

// 기본 화살표 함수
let arrowFunc1 = (x, y) => {
  return x + y;
};

// 함수 내에 한 줄만 쓸 거라면 이렇게 축약 가능
let arrowFunc2 = (x, y) => x + y;

function test(x) {
  return x;
}

// 매개 변수가 한 줄일 때는 (x) => x 처럼 괄호도 생략 가능
let arrowFunc3 = (x) => x;

 

❗️ 화살표 함수엔 arguments 객체가 없다!

function nomalFunc() {
  console.log(arguments);
};

const arrowFunc = () => {
  console.log(arguments);
};

nomalFunc(1, 2, 3) // [1, 2, 3]
arrowFunc(1, 2, 3) // arguments is not defined

 

❗️ 화살표 함수는 this 를 바인딩하지 않는다.

this 가 없어 상위 환경에서의 this 를 참조한다.

const person = {
  name: "aoto",
  age: 20,
  isMarried: false,
  sayHello: function () {
    console.log(`Hello, My name is ${this.name}`);
  },
  sayHi: () => console.log(`Hi, My name is ${this.name}`),
};

person.sayHello(); // Hellow, My name is aoto
person.sayHi(); // Hi, My name is undefined

 

let obj = {
  outer: function () {
    console.log(this); // {outer: ƒ}
    let innerFunc = () => {
      console.log(this); // {outer: ƒ}
    };
    innerFunc();
  },
};

obj.outer();

 

정리가 더 필요할 것 같다 🥵