본문 바로가기

JavaScript/Basic-Javascript

자바스크립트 정리하며 배우기[25] - This[4] : call 과 apply 메서드를 이용한 명시적인 this 바인딩

안녕하세요. Tay 입니다.

이제까지 호출 방식에 따라서 바인딩 되는 this 를 확인해봤습니다.

이번에는 명시적으로 this 바인딩을 지정하는 방법에 대해서 알아보겠습니다.

 

apply 메서드

function.apply(thisArg, argArray);

  • thisArg : 함수 내부에서 사용한 this 에 바인딩 할 객체
  • argArray : 함수 호출시 넘길 인자들 배열

1) index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="apply.js"></script>
  </body>
</html>

2) apply_call.js

apply

function Person(name, national, gender) {
  this.name = name;
  this.national = national;
  this.gender = gender;
}

let kim = {};

Person.apply(kim, ["geuntae", "kor", "male"]);
console.log(kim);
  1. 생성자 함수 Person 을 선언한다.
  2. 빈 객체 kim 을 선언한다.
  3. function apply 를 통해서 kim 객체에 배열을 함수인자로 전달한다.
  4. 명시적으로 kim 객체에 this를 바인딩 했다.

 

Github Commit

 

결과 :

kim 객체에 프로퍼티가 정상적으로 생성됐다.

 

 

call 메서드

function.call(thisArg, parameters)

  • thisArg : 함수 내부에서 사용한 this 에 바인딩 할 객체
  • parameters : 넘길 인자들을 하나씩 열거

1) apply_call.js

 

lee 객체 와 call

function Person(name, national, gender) {
  this.name = name;
  this.national = national;
  this.gender = gender;
}

let kim = {};

Person.apply(kim, ["geuntae", "kor", "male"]);
console.log(kim);

let lee = {};

Person.call(lee, "sedol", "kor", "female");
console.log(lee);
  1. kim 객체와 lee 객체를 비교해보자.
  2. 빈 객체 lee 를 생성했다.
  3. call 메서드로 this 를 바인딩해서 프로퍼티를 생성

 

Github Commit

 

결과 :

정상적으로 lee 객체에 프로퍼티가 생성 된 것을 확인할 수 있다.

 

 

이 글은 개인 공부목적으로 작성되었습니다.

정보가 잘못 되거나 궁금한 사항은 댓글로 부탁드립니다!! 읽어주셔서 감사합니다.