Javascript

[javascript] apply() 메서드를 배워보자

lemonarr🍋 2024. 2. 8. 14:07

-자바스크립트에서 함수를 호출하는 내장 메서드 방법 중 하나.

-일반적으로 함수명(파라미터)의 형식으로 호출하지만, apply메서드는 파라미터로

함수에서 사용할 this 객체와 호출하는 함수로 전달할 파라미터를 입력받는다.

-함수를 호출하는 동안 함수의 this 값을 설정하고, 함수에 인수를 배열로 전달할 수 있도록 도와줌.

 

 

 

apply (this로 사용될 값, 호출할 함수의 매개변수를 받을 배열)

func.apply(thisArg, [argsArray]);

 

 

 

apply 메서드의 특징

 

-함수를 어떻게 호출했는지 상관하지 않고 this를 지정할 수 있다.

-특정 함수를 호출할 때 '매개변수'를 배열로 넣어야 하는 경우 활용한다.

-행, 혹은 열로 정리해주는 함수 어플리케이션이다.

 

 

예시를 살펴보자.

const person = {
  name: 'John',
  age: 30
};

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

sayHello.apply(person, ['Hello']); // 출력: "Hello, John!"

 

 

const numbers = [1, 2, 3, 4, 5];
const sum = Array.prototype.reduce.apply(numbers, [(a, b) => a + b]);
console.log(sum); // 출력: 15

 

 

Apply( ) 와 내장함수 Math.max/min( )

Mdn에서 가져온 예시이다.

 

const numbers = [5, 6, 2, 3, 7];

const max = Math.max.apply(null, numbers);

console.log(max);
// Expected output: 7

const min = Math.min.apply(null, numbers);

console.log(min);
// Expected output: 2

 

예시를 보니 Math.max() 메서드와 종종 같이 사용되는 듯하다.

apply와 내장함수를 사용하여  배열과 루프없이 보다 효과적으로 처리된다. 

(※사용하는 배열 변수의 수가 수만을 초과하는 경우에는 분할하여 사용한다.)

 

 

 

 

 

참고문헌

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/apply