23/03/10 기준
.call()
함수는 내장함수(built-in function) 중 하나입니다. 자바스크립트에서 함수를 호출할 때 사용할 수 있는 함수 중 하나로, 특정 객체에 대해 함수를 호출하는 방법을 제공합니다.
.call()
함수는 다음과 같은 형식으로 사용됩니다.
javascriptCopy code
functionName.call(thisArg, arg1, arg2, ...);
여기서 **thisArg
**는 함수를 호출할 때 **this
**로 참조할 객체를 의미하며, arg1
, arg2
, ... 등은 함수에 전달할 인자(argument)를 나타냅니다.
예를 들어, 다음과 같은 객체와 함수가 있다고 가정해보겠습니다.
javascriptCopy code
const person = {
name: 'John',
age: 30,
greeting: function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
};
위 코드에서 person
객체는 name
, age
, greeting
속성을 가지고 있으며, greeting
속성은 함수입니다. 이제 greeting
함수를 호출하면 **this
**는 person
객체를 참조하게 됩니다.
javascriptCopy code
person.greeting(); // 출력: Hello, my name is John and I am 30 years old.
하지만, greeting
함수를 다른 객체에서 호출하게 되면 **this
**가 다른 객체를 참조하게 됩니다. 이때, .call()
함수를 사용하여 **this
**가 참조할 객체를 명시적으로 지정할 수 있습니다.
javascriptCopy code
const anotherPerson = {
name: 'Mary',
age: 25
};
person.greeting.call(anotherPerson); // 출력: Hello, my name is Mary and I am 25 years old.
위 코드에서 .call()
함수를 사용하여 greeting
함수를 anotherPerson
객체에서 호출하였습니다. 이제 greeting
함수에서 **this
**는 anotherPerson
객체를 참조하게 됩니다.