[자바스크립트] call()/ apply()/ bind()

트릴로니·2022년 7월 23일

자바스크립트

목록 보기
21/31

call() / apply() / bind()

  • 함수의 this 키워드를 조작하거나 인자를 전달하기 위해 쓸 수 있다.

call()

  • 모든 함수를 호출할 때 사실 call()이 호출된다.
function a() {
	console.log('hi')
}
//a()
a.call()

예시) archer 객체에서 wiard객체의 heal함수를 쓰고 싶다

const wizard = {
	name: 'Merlin'
    health: 50,
    heal() {
    	return this.health = 100;
    }
}

const archer = {
	name: 'Merlin'
    health: 30,
}

wizard.heal.call(archer)
  • 첫번째 파라미터에 함수를 어떤 객체에 붙이고 싶은지 넣어준다.

    call a method of an object, substituting another object for the current object

  • 이외 파라미터: 메소드에 넣어줄 값

const wizard = {
	name: 'Merlin'
    health: 50,
    heal(num1, num2) {
    	return this.health += num1 + num2;
    }
}

const archer = {
	name: 'Merlin'
    health: 30,
}

wizard.heal.call(archer, 40, 80)

apply

  • call()과의 차이점은 파라미터를 배열로 메소드에 패스해준다.
const wizard = {
	name: 'Merlin'
    health: 50,
    heal(num1, num2) {
    	return this.health += num1 + num2;
    }
}

const archer = {
	name: 'Merlin'
    health: 30,
}

wizard.heal.apply(archer, [40, 80])

bind

  • 함수를 즉시 호출하는 call과 apply와 달리, bind는 다른 컨텍스트와 파라미터를 붙여 함수를 반환한다.
  • bind는 특정 this키워드나 컨텍스트를 붙인 함수를 나중에 호출하고 싶을 때 쓰인다.
const wizard = {
	name: 'Merlin'
    health: 50,
    heal(num1, num2) {
    	return this.health += num1 + num2;
    }
}

const archer = {
	name: 'Merlin'
    health: 30,
}

const healArcher = wizard.heal.bind(archer, 40, 80)
healArcher()
// 150
function multiply(a,b) {
	return a*b
}

let multiplyByTwo = multiply.bind(this, 2)
//this === Window
cosnsole.log(multiplyByTwo)
//[Function]
cosnsole.log(multiplyByTwo(4))
//8
  • bind는 함수를 반환하기 때문에 특정 파라미터를 미리 지정해 놓을 수 있다.

결론

  • call과 apply는 다른 객체의 메소드를 쓰고 싶을 때 유용하다.
  • bind는 호출하고 싶은 함수에 특정 컨텍스트나 this 키워드를 붙여서 나중에 호출하고 싶을 때 유용하다.

0개의 댓글