화살표 함수 (this 바인딩, arguments 객체, 생성자 함수로 사용 불가, super 키워드와 화살표 함수) 의 자세한 내용

민정이등장·2024년 10월 24일
0
post-thumbnail

📌 this 바인딩

this 바인딩은 JavaScript에서 함수나 메서드가 호출될 때, 그 함수나 메서드가 속하는 객체를 참조하는 특수한 키워드이다. this의 값은 호출 방식에 따라 달라진다.

1. 전역 컨텍스트에서의 this

전역 코드에서 this는 전역 객체를 참조한다. 브라우저에서는 전역 객체가 window다.

console.log(this); // window (브라우저에서)

2. 함수 호출에서의 this

일반적인 함수 호출에서는 thisundefined가 된다 (엄격 모드에서는).

function myFunction() {
    console.log(this);
}
myFunction(); // undefined (엄격 모드에서는)

3. 메소드 호출에서의 this

객체의 메소드로 호출될 경우, this는 그 메서드를 호출한 객체를 참조한다.

const obj = {
    value: 42,
    showValue: function() {
        console.log(this.value);
    }
};
obj.showValue(); // 42

4. 생성자 함수에서의 this

생성자 함수에서 this는 새로 생성된 객체를 참조한다.

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

5. 화살표 함수에서의 this

화살표 함수는 자신만의 this를 가지지 않으며, 정의된 위치에서 상위 컨텍스트의 this를 사용한다.

const obj = {
    value: 42,
    showValue: function() {
        const arrowFunc = () => {
            console.log(this.value);
        };
        arrowFunc();
    }
};
obj.showValue(); // 42

6. call, apply, bind 메소드

이 메소드들은 함수의 this를 명시적으로 설정할 수 있게 해준다.

  • call: 함수를 호출하고, this를 첫 번째 인자로 지정한다.
function greet() {
    console.log(`Hello, ${this.name}`);
}
const user = { name: 'Alice' };
greet.call(user); // Hello, Alice
  • apply: call과 비슷하지만, 인자를 배열로 받는다.
function sum(a, b) {
    return a + b;
}
console.log(sum.apply(null, [5, 10])); // 15
  • bind: 새로운 함수를 반환하고, this를 설정한다.
const boundGreet = greet.bind(user);
boundGreet(); // Hello, Alice

📌 arguments 객체

화살표 함수에서의 arguments 객체는 일반 함수와 다르게 사용되지 않는다. arguments 객체는 함수의 인자들을 배열 형태로 접근할 수 있게 해주는 유사 배열 객체인데, 화살표 함수에서는 arguments 객체가 존재하지 않는다.

1. 일반 함수에서의 arguments

일반 함수 내에서는 arguments 객체를 통해 전달된 인자에 접근할 수 있다.

function myFunction() {
    console.log(arguments);
}
myFunction(1, 2, 3); // { '0': 1, '1': 2, '2': 3 }

2. 화살표 함수에서의 arguments

화살표 함수는 arguments 객체를 가지지 않으며, 만약 사용하려고 하면 외부 스코프의 arguments 객체를 참조하게 된다.

const myArrowFunction = () => {
    console.log(arguments); // 외부의 arguments 객체를 참조
};

function test() {
    myArrowFunction(1, 2, 3); // 이 경우, test() 함수의 arguments를 참조
}
test(4, 5, 6); // { '0': 4, '1': 5, '2': 6 }

3. 해결 방법

화살표 함수에서 arguments를 사용하고 싶다면, 일반 함수로 선언하거나, 나머지 매개변수(...args)를 사용하는 것이 좋다.

일반 함수 사용 예시:

const myFunction = function() {
    console.log(arguments);
};
myFunction(1, 2, 3); // { '0': 1, '1': 2, '2': 3 }

나머지 매개변수 사용 예시:

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

결론

화살표 함수는 arguments 객체를 지원하지 않지만, 외부 스코프의 arguments를 참조하거나, 나머지 매개변수를 사용하여 전달된 인자에 접근할 수 있다.


📌 생성자 함수로 사용 불가

화살표 함수는 생성자 함수로 사용할 수 없다.

1. this 바인딩

화살표 함수는 자신만의 this 바인딩을 가지지 않고, 정의된 외부 스코프의 this를 그대로 사용한다. 생성자 함수는 새로운 객체를 생성할 때 this를 그 객체를 참조해야 하는데, 화살표 함수는 이를 지원하지 않는다.

const Person = (name) => {
    this.name = name; // 이 때의 this는 Person을 가리키지 않음
};

const person1 = new Person('Alice'); // TypeError: Person is not a constructor

2. new 키워드

생성자 함수는 new 키워드를 사용해 호출되며, 이때 새로운 객체가 생성된다. 화살표 함수는 new로 호출할 수 없고, 호출 시 TypeError를 발생시킨다.

const MyConstructor = () => {};
const instance = new MyConstructor(); // TypeError: MyConstructor is not a constructor

3. prototype 속성

생성자 함수는 일반적으로 prototype 속성을 가지며, 이를 통해 객체 간 상속을 구현할 수 있다. 화살표 함수는 prototype 속성을 갖지 않는다.

const MyConstructor = function() {};
console.log(MyConstructor.prototype); // { }
const MyArrowFunction = () => {};
console.log(MyArrowFunction.prototype); // undefined

결론

화살표 함수는 this를 외부에서 상속받고, new로 호출할 수 없으며, prototype 속성을 가지지 않기 때문에 생성자 함수로 사용될 수 없다. 일반 함수나 클래스를 사용해 생성자 함수를 정의하는 것이 적합하다.


📌 super 키워드와 화살표 함수

화살표 함수와 super 키워드는 JavaScript에서 각각 중요한 역할을 한다.

1. 화살표 함수

주요 특징

  • 간결한 문법: 일반 함수보다 더 짧은 문법으로 작성할 수 있다.
  • this 바인딩: 화살표 함수는 자신의 this를 가지지 않고, 외부 스코프의 this를 참조한다. 따라서 객체 메서드로 사용될 때 this의 동작이 예상과 다를 수 있다.
  • arguments 객체 없음: 화살표 함수는 arguments 객체를 갖지 않으며, 대신 나머지 매개변수를 사용해야 한다.

예제:

const add = (a, b) => a + b;
console.log(add(2, 3)); // 5

2. super 키워드

super는 클래스에서 부모 클래스의 메서드나 속성을 호출할 때 사용된다. 이는 ES6에서 도입된 클래스 구문과 관련이 있다. super는 주로 다음과 같이 사용된다:

  • 부모 클래스의 생성자 호출: 자식 클래스의 생성자에서 부모 클래스의 생성자를 호출할 때 사용한다.
  • 부모 클래스의 메서드 호출: 자식 클래스에서 부모 클래스의 메서드를 호출할 때 사용한다.

예제:

class Parent {
    constructor(name) {
        this.name = name;
    }

    sayHello() {
        console.log(`Hello, ${this.name}!`);
    }
}

class Child extends Parent {
    constructor(name) {
        super(name); // 부모 클래스의 생성자 호출
    }

    greet() {
        super.sayHello(); // 부모 클래스의 메서드 호출
    }
}

const child = new Child('Alice');
child.greet(); // Hello, Alice!

화살표 함수와 super

화살표 함수는 super를 사용할 수 없다. 이는 화살표 함수가 this를 외부 스코프에서 가져오기 때문이다. 따라서 super 키워드를 사용하는 메서드에서는 화살표 함수를 사용할 수 없다.

예제:

class Parent {
    sayHello() {
        console.log('Hello from Parent!');
    }
}

class Child extends Parent {
    greet = () => {
        super.sayHello(); // 오류 발생
    }
}

위의 코드에서 super를 사용한 화살표 함수 greet는 올바르게 동작하지 않으며, super는 클래스를 통해 정의된 일반 메서드 내에서만 사용할 수 있다.

결론

화살표 함수는 간편한 함수 정의를 가능하게 하지만, thissuper의 바인딩 방식 때문에 일부 상황에서는 사용이 제한된다. 클래스 구조 내에서 super를 사용할 때는 반드시 일반 메소드를 정의해야 한다.

profile
킵고잉~

0개의 댓글