[Javascript] 일반 함수, 화살표 함수 차이

해피몬·2023년 1월 12일
0
post-thumbnail

문법(Syntax)

일반 함수

function 키워드를 사용하여 정의합니다.

function greet() {
  return "Hello!";
}

화살표 함수

=>를 사용하여 더 간결하게 정의합니다.

const greet = () => "Hello!";

this 바인딩

바인딩(Binding)은 this가 참조하는 객체를 결정하는 과정을 의미합니다. 즉, 특정 컨텍스트(함수나 메서드) 내에서 this가 어떤 객체를 가리킬지 묶어 놓는 것을 바인딩이라고 합니다.

일반 함수

호출 방식에 따라 this가 동적으로 바인딩됩니다. 일반 함수는 호출될 때 그 함수를 호출한 객체에 따라 this가 달라질 수 있습니다.

const obj = {
  name: "Alice",
  regularFunction: function() {
    console.log(this.name);
  }
};
obj.regularFunction(); // "Alice"

화살표 함수

화살표 함수는 자신의 this를 가지지 않으며, 외부 스코프의 this를 자동으로 상속받습니다. 즉, 작성된 위치의 this가 유지됩니다.

const obj = {
  name: "Alice",
  arrowFunction: () => {
    console.log(this.name);
  }
};
obj.arrowFunction(); // undefined (화살표 함수의 this는 전역 객체를 가리킴)

arguments 객체

일반 함수

호출 시 전달된 인자 목록을 담은 arguments 객체를 사용할 수 있습니다.

function showArgs() {
  console.log(arguments);
}
showArgs(1, 2, 3); // [1, 2, 3]

화살표 함수

arguments 객체를 가지고 있지 않으며, 필요할 경우 rest parameter (...args)를 사용해야 합니다.

const showArgs = (...args) => {
  console.log(args);
};
showArgs(1, 2, 3); // [1, 2, 3]

생성자 함수로 사용 가능 여부

일반 함수

new 키워드를 사용하여 생성자 함수로 사용할 수 있습니다.

function Person(name) {
  this.name = name;
}
const alice = new Person("Alice");
console.log(alice.name); // "Alice"

화살표 함수

생성자 함수로 사용할 수 없으며, new 키워드로 호출하면 오류가 발생합니다.

const Person = (name) => {
  this.name = name;
};
const alice = new Person("Alice"); // TypeError: Person is not a constructor

prototype 프로퍼티

일반 함수

prototype 프로퍼티를 가지므로 프로토타입을 활용할 수 있습니다.

// 일반 함수 정의
function Person(name) {
  this.name = name;
}

// prototype에 메서드 추가
Person.prototype.sayHello = function() {
  console.log(`Hello, my name is ${this.name}`);
};

// 인스턴스 생성
const person1 = new Person('Alice');
person1.sayHello(); // Hello, my name is Alice

// prototype 확인
console.log(Person.prototype); 
// { sayHello: [Function (anonymous)] }

화살표 함수

prototype 프로퍼티가 없으므로 프로토타입 관련 기능을 사용할 수 없습니다.

// 화살표 함수 정의
const Animal = (name) => {
  this.name = name;
};

// 화살표 함수에는 prototype이 없음
console.log(Animal.prototype); 
// undefined

// 인스턴스 생성 시 오류 발생
// const animal1 = new Animal('Dog'); // TypeError: Animal is not a constructor
profile
슬기로운개발생활🤖

0개의 댓글