Javascript

[Javascript] call, apply, bind

yangjoy 2022. 1. 19. 17:25

call, apply, bind?

✔️ 함수 호출 방식과 관계없이 this를 지정할 수 있음.

 

call

✔️ 모든 함수에 서 사용할 수 있으며, this를 특정값으로 지정할 수 있다.'

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

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

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

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

//call의 첫번째 매개변수는 this에 들어갈 객체
//call의 두번째 매개변수부터는 해당 함수의 매개변수 자리에 들어갈 인수들을 넣어준다.
update.call(mike, 1999, "singer")
console.log(mike);//{name:"mike", birthYear:1999, occupation:"singer"}

 

apply

✔️ apply는 함수 매개변수를 처리하는 방법을 제외하면 call과 완전히 같다.

✔️ call은 일반적인 함수와 마찬가지로 매개변수를 직접 받지만, apply는 매개변수를 배열로 받는다

✔️ 그래서 배열요소를 함수 매개변수로 사용할 때 유용하다.

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

const tom = {
	name:"Tom",
}

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

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

update.apply(mike, [1999, "singer"]);
console.log(mike); //{name: 'Mike', birthYear: 1999, occupation: 'singer'}

 

bind

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

 

const mike = {
	name:"Mike",
}

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

const updateMike = update.bind(mike);

updateMike(1999,"police");
console.log(mike);//{name: 'Mike', birthYear: 1999, occupation: 'police'}
const user = {
    name:"Mike",
    showName:function(){
        console.log(`hello, ${this.name}`);
    },
}

user.showName();

let fn = user.showName;

// fn.call(user);
// fn.apply(user);

let boundFn = fn.bind(user);
boundFn();

 

Reference