Call, Apply, Bind

Bruce·2021년 12월 6일

프론트엔드 코어

목록 보기
9/31

0. 함수호출 call, apply, bind

자바스크립트 메소드 2가지 유형
1. 숫자, 배열, 문자열.. 메소드(math, map, split..)
2. 함수 메소드(call, apply, bind)
함수호출의 2가지 유형
1. 함수명 뒤에 ()중괄호
2. call, apply, bind

1. call과 apply

사용법:
fn.call(thisArg [,arg1[,arg2[,...]]])

fn.apply(thisArg, [argsArray])

1) call, apply의 첫번째 인자는 this, 두번째 인자는 개체를 위한 인수가 온다. 아래 예제1처럼 apply의 두번째 인자는 배열형태로 받는다.

예제1

const example = function(a, b, c) {
  return a + b + c;
};
example(1, 2, 3);
example.call(null, 1, 2, 3);
examply.apply(null, [1, 2, 3]);

예제1-2

const obj = {
  string: 'zero',
  yell: function() {
    alert(this.string);
  };
};
 
const obj2 = {
  string: 'what?'
};
    
obj.yell(); // 'zero';
obj.yell.call(obj2); // 'what?'
2) 함수에는 arguments라는 유사배열이 있는데, 이 arguments를 조작할때 함수의 메소드들이 사용된다.

예제2

   const example = function() {
     console.log(Array.prototype.join.call(arguments));
   };
   example(1, 'string', true); // '1, string, true'

보기와 같이 아규먼트는 유사배열임에도 불구하고, call로 this를 바꿔주어, 배열의 메소드를 사용 가능하게 해준다.

2. bind

사용법:
fn.bind(thisArg [,arg1[,arg2[,...]]])

bind는 call, apply 같이 함수가 가리키는 this를 바꾸지만, 호출은 되지않는다. 따라서 변수에 할당하여 호출 한다.
const student = person2.study.bind(person1) // 변수에 할당
student() // 호출

3. Examples

Call:

function cat (q, w, e) {
  return console.log(this.dog ,q,w,e);
};
cat(1, 2, 3);

const that = {
    dog: 'bark'
}

cat.call(that, 1, 2, 3);

// expected output: undefined 1 2 3
// expected output: bark 1 2 3

Apply:

function cat (q, w, e) {
  return console.log(this.dog ,q,w,e);
};
cat(1, 2, 3);

const that = {
    dog: 'bark'
}

cat.apply(that, [1, 2, 3]);

// expected output: undefined 1 2 3
// expected output: bark 1 2 3

Bind:

const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
};

const unboundGetX = module.getX;
console.log(unboundGetX());
// expected output: undefined
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42
profile
Figure it out yourself

0개의 댓글