본문 바로가기

Programming/TIL

.call & .apply Methods

함수를 실행하는 세가지 방법들.

* 단순히 소괄호를 사용하는 방법 말고 메소드를 이용해 실행할 수 있다.

function foo() {
  return 'bar'
}

foo()
foo.call()
foo.apply()

특히, .call, .apply 호출은 명시적으로 this를 지정하고 싶을 때 사용한다.

∴ 첫번째 인자가 항상 this값이 된다.

 

** .call과 .apply 메소드의 차이점 : .apply 호출은 배열을 인자로 받는다. **

// null을 this로 지정한다. Math는 생성자가 아니므로 this를 지정할 필요가 없다.
Math.max.apply(null, [5,4,1,6,2]) // 6 

Array prototype에서 메소드를 빌려와 this를 넘겨 실행할 수도 있다.

아래 예시들을 참고해보자.

 

예제 1.

// '피,땀,눈물'을 this로 지정한다.
''.split.call('피,땀,눈물', ',')

// 다음과 정확히 동일한 결과를 리턴한다.
'피,땀,눈물'.split(',')

예제2.

let allDivs = document.querySelectorAll('div'); // NodeList라는 유사 배열이다.
// allDivs를 this로 지정한다.
[].map.call(allDivs, function(el) {
  return el.className
})

아래는 객체 지향 프로그래밍에서 자주 볼 수 있는 예시다.

function Product(name, price) {
  this.name = name
  this.price = price
}

function Food(name, price) {
  Product.call(this, name, price)
  // 인자가 많으면 Product.apply(this, arguments) 가 더 유용하다.
  
  this.category = 'food'
}

let cheese = new Food('feta', 5000) // cheess는 Food이면서 Product이다.

 

'Programming > TIL' 카테고리의 다른 글

ESlint  (0) 2020.12.02
.bind Method  (0) 2020.12.01
[this] Keyword  (0) 2020.12.01
Arrow Function  (0) 2020.12.01
Node.js Related Tools  (0) 2020.11.30