apply, call, bind method

Chan·2023년 1월 12일
0

javascript

목록 보기
2/6
post-thumbnail

apply, call, bind method

apply, call method의 본질적인 기능은 함수를 호출 하는 것

apply와 call 메소드는 함수를 호출하면서 첫 번째 인수로 전달한 특정 객체를 호출한 함수의 this에 바인딩

apply, call 부터 살펴보겠다.

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

→ null의 역할은 this를 대체 하는 것이다.

→ 이때 call, apply의 차이점은 함수의 인수를 배열로 전달하느냐, 리스트 형식으로 전달하느냐의 차이만 존재

this가 다르다면 즉 넘긴 객체가 다르다면 반환 값도 당연히 다르다.

const person1 = {name : "jacob"};
const person2 = {name : "master jung"};

function greet() {
	return 'Hello, ${this.name}';
}

greet() // Hello, undefined 
greet.call(person1}; // Hello, jacob
greet.call(person2); // Hello, master jung 

% 주의할 점

당연한 이야기지만 프로퍼티가 같아야 한다.

const person1 = {Name : "jacob"};
function greet() {
	return 'Hello, ${this.name}';
}

greet() // Hello, undefined 
greet.call(person1}; // Hello, undefined

Name 과 name은 같지 않기 때문에 undefined가 출력이 된다.

bind는 apply와 call 메소드와 달리 함수 호출을 하지 않는다.

var obj = {
  string: 'zero',
  yell: function() {
    alert(this.string);
  }
};
var obj2 = {
  string: 'what?'
};
var yell2 = obj.yell.bind(obj2);
yell2(); // 'what?'

→ apply, call이었다면 obj.yell.call(obj2); 를 하자마자 what?이 나왔다.

apply, call, bind는 왜 사용할까

  1. 함수의 arguments를 조작할 때

    arguments란 함수에 들어온 인자를 배열 형식으로 나타낸다 ( 유사 배열임 , 배열 X)

    function example() {
      console.log(arguments);
    }
    example(1, 'string', true); // [1, 'string', true]

하지만 유사 배열이기 떄문에 배열 속성은 적용 안된다. ( join 함수 쓸 수 없음 )

function example2() {
  console.log(arguments.join());
}
example2(1, 'string', true); // Uncaught TypeError: arguments.join is not a function

이때 apply, call 을 사용하여 해결

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

→ 배열의 join 함수를 빌려와서 call을 사용, 이때 arguments는 this에 해당이 된다.

(번외)

=⇒ 이러한 번거로움을 해결하기 위해 Rest파라미터가 도입되었다고 하긴함 ,,

function example3(...args) {
  console.log(args.join());
}
example3(1, 'string', true); // '1,string,true'
  1. 함수를 어떻게 호출했는 지 상관하지 않고 this 값을 설정할 때

    this 값을 직접 지정해서 함수를 호출하고 싶을 때 사용한다,,

    함수가 어느 객체 안에 존재하고 싶을 때 즉 조작할 때 많이 사용될 것 같다.

    위처럼 단순 한 예시 말고 복잡한 코드 속에서 의도적으로 조작하는 예시를 찾고 싶었지만 잘 안나온다

    많이 안쓰이나..? ㅎ


책 보면서 이해 안됐던 점

const person = {
	name : 'Lee', 
	foo(callback){
	//1 
	setTimeout(callback, 100);
}
};
person.foo(function(){
	console.log('Hi! my name is ${this.name}.'); 
});

person.foo 를 하면 person 이라는 객체가 이미 생성이 되어서 foo 함수를 호출을 하는 거니깐

this를 직접 지정해서 함수 호출을 하지 않아도 this.name에 자동적으로 Lee가 들어가지 않을까 하는 생각을 했다…

person.foo의 콜백 함수는 보조적인 역할을 하는 함수이기 때문에 this를 전달을 해야지만 외부함수와 콜백 함수의 this가 같아져 문제 발생 X

this 전달을 해야 함.

0개의 댓글