apply,call함수

정중식·2023년 2월 3일
0

자바스크립트

목록 보기
6/20

apply

실행할함수.apply(적용할곳);

var person = {
    hello : function(){
      console.log(this.name + 'hi')
    }
}
  
var person2 = {
    name : '정중식'
}

person.hello()라는 함수를 person2에서도 쓰고싶을때의 상황.
(직접 코딩해서 집어넣어도되나 그게 불가능한 경우나, 귀찮은 경우 apply를 사용할 수 있다.)

apply는 이 함수를 실행하는데.. 저기 오브젝트에다가 적용해서 실행해주세요~ 라는 뜻이다.
혹은, person.hello()라는 함수를 쓰는데, person2라는 오브젝트에 있는 함수처럼 실행하라는 뜻이다.

var person = {
    hello : function(){
      console.log(this.name + 'hi')
    }
}
  
var person2 = {
    name : '정중식'
}

person.hello.apply(person2);

call

var person = {
    hello : function(){
      console.log(this.name + 'hi')
    }
}
  
var person2 = {
    name : '정중식'
}

person.hello.apply(person2);
person.hello.call(person2);

apply와 call은 실행 결과도 똑같고 사용법도 똑같다.
차이점은, 파라미터를 [array]로 한꺼번에 집어넣냐, 못넣냐 차이이다.
apply는 파라미터로 array를 넣을 수 있고, call는 일반 함수처럼만 집어넣을 수 있다.

person.hello.apply(person2,[1,2,3]);
person.hello.call(person2, 1,2,3);

▲ 파라미터 집어넣는 방법만 좀 차이가 있을뿐, call, apply의 실행내용은 똑같다.

profile
내 가치를 찾아서

0개의 댓글