Javascript

[Javascript] setTimeout / setInterval /call & apply & bind

sian han 2022. 12. 3. 18:20
  • setTimeout : 일정시간이 지난 후 함수 실행
  • setInterval : 일정시간 간격으로 함수를 반복
  • clearTimeout : 일정시간 후 실행 예정인 함수를 없앰 (setTimeout 무효화)

setTimeout(실행될 함수, 시간);

인수가 더 필요하다면 시간 뒤에 적어준다

 

ex ) setTimeout(showName, 3000, 'sian');

        - 여기서 세번째 인자 sian은 3초 후 실행될 함수 showName 의 인자이다

function showNmae(name){
	console.log(name);
}

 

 


※ call & apply & bind

  - 함수 호출 방식과 관계없이 this 를 지정할 수 있다

 

▶ call

call 메서드는 모든 함수에서 사용할 수 있으며, this 를 특정값으로 지정할 수 있다.

const mike = {name : "mike"};
const tom = {name : "tom"};

function showThisName(){
	console.log(this.name);
}

showThisName();
showThisName.call(mike); //mike

call() 의 첫번째 인자는 this 로 사용할 값이고,

그 뒤에 인자가 더 있으면 그 매개변수를 호출하는 함수의 인자로 사용된다

 

 

function update(birthYear, occupation){
	this.birthYear = birthYear;
    this.occupation = occupation;
}

update.call(mike, 1999, "singer")

update 함수를 통해 mike 객체의 key 가 추가되었다. (name) => (name, birthYear, occupation)

 

 

▶ apply

  • 함수 매개변수를 처리하는 방법을 제외하면 call 과 완전히 같다.
  • call 은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply는 매개변수를 배열로 받는다
  • 배열 요소를 함수 매개변수로 사용할때 용이하다

 

▶ bind

함수의 this 값을 영구히 바꿀 수 있다.

 

const mike = {
	name : "mike",
};

function update(birthYear, occupation){
	this.birthYear = birthYear;
    this.occupation = occupation;
}

const updateMike = update.bind(mike);

updateMike(1980, "police"); // 완전합쳐짐
console.log(mike);