[JS] 함수 호출 call, apply, bind

이한솔·2023년 11월 20일
0

JavaScript

목록 보기
8/11

자바스크립트에서 this는 함수가 호출될 때 결정되며, 호출 문맥에 다라 다르게 바인딩이 된다. 일반적으로 this 바인딩 규칙은 다음과 같다.

  1. 전역 객체 바인딩
    : 함수가 일반적인 함수 호출로 실행되면, this는 전역 객체에 바인딩이 된다. 브라우저 환경에서 전역 객체는 window 이다.
function globalFunction() {
  console.log(this); // 전역 객체 (브라우저에서는 window)
}

globalFunction();
  1. 매소드 호출 시 바인딩
    : 객체의 메소드로 함수가 호출되면, this는 해당 객체에 바인딩 된다.
const myObject = {
  myMethod: function() {
    console.log(this); // myObject
  }
};

myObject.myMethod();
  1. 생성자 함수에서의 바인딩
    : 생성자 함수로 객체 인스턴스를 생성할 때 this는 생성된 인스턴스에 바인딩 된다.
function MyClass() {
  this.property = "Hello, this is a property.";
}

const myInstance = new MyClass();
console.log(myInstance.property); // Hello, this is a property.
  1. 화살표 함수에서의 바인딩
    : 화살표 함수는 자체적인 this를 가지지 않고 외부 스코프의 this 를 그대로 사용한다.
const arrowFunction = () => {
  console.log(this); // 외부 스코프의 this를 사용
};

arrowFunction.call({}); // 외부 스코프의 this를 사용
  1. 함수 내부에서의 call, apply 등의 메소드를 사용한 바인딩
    : call 또는 apply 등의 메소드를 사용하여 명시적으로 this를 특정 값으로 설정할 수 있다.
function explicitFunction() {
  console.log(this);
}

const explicitObject = { name: "Explicit Object" };

explicitFunction.call(explicitObject); // explicitObject

여기서 함수 내부에서 call, apply, bind 메소드를 사용한 바인딩에 대해서 좀더 알아보고자 한다.

Function.prototype.call()

fun.call(thisArg, arg1, arg2, ...)

함수를 호출하면서 특정 객체를 thisArg로 설정하고 필요한 매개 변수를 전달한다.

Function.prototype.apply()

fun.apply(thisArg, [argsArray])

함수를 호출하면서 특정 객체는 thisArg로 설정하고, 매개변수를 배열로 전달한다.

bind

const newFunc = func.bind(thisArg, arg1, arg2, ...)

특정 객체를 thisArg로 설정하고, 필요한 매개 변수를 미치 바인딩한 새로운 함수를 생성한다.

function greet(name) {
  console.log(`Hello, ${name}!`);
}

greet.call(null, 'John');  // Hello, John!
greet.apply(null, ['Jane']);  // Hello, Jane!

const greetJohn = greet.bind(null, 'John');
greetJohn();  // Hello, John!

요약

1. call, apply, bind는 함수의 this를 사용자가 원하는 대로 바인딩 할 수 있게 한다. 2. call, apply는 함수를 호출 및 적용되고, bind()는 함수를 호출하지 않고 새로운 함수를 반환한다.
profile
개인 공부용

0개의 댓글