Javascript

call, apply, bind

킹king 2021. 2. 20. 17:14
반응형
let red = {
	fruits: 'apple'
};

let yellow = {
	fruits: 'banana'
};

const say = function() {
	console.log(`${this.fruits} is good!`);
};

// 각각의 object가 하나의 say를 쓰고 싶다면?

 

 


 

 

1. call

say.call(red) // apple is good!;
say.call(yellow) // banana is good!;

이렇게 쿨하게 가져다가 쓸 수 있다.

 

1-1) 만약 function에 인자가 있다면

let red = {
	fruits: 'apple'
};

const say = function(country) {
	console.log(`${this.fruits}(from ${country}) is good!`);
};

say.call(red, 'korea'); // apple(from korea) is good!

그냥 쉼표 쓰고 인자를 써주면 된다.

 

1-2) 그 인자가 여러개라면

let red = {
	fruits: 'apple'
};

const say = function(country, num1, num2) {
	console.log(`Number ${num1 + num2} ${this.fruits}(from ${country}) is good!`);
};

say.call(red, 'korea', 2, 3); // Number 5 apple(from korea) is good!

그냥 계속 쉼표 쓰고 인자를 써주면 된다.

 

 

2. apply

여러개의 인자를 하나의 arr에 묶었을 경우 apply를 씀.

let red = {
	fruits: 'apple'
};

const say = function(country, num1, num2) {
	console.log(`Number ${num1 + num2} ${this.fruits}(from ${country}) is good!`);
};

let arr = ['korea', 2, 3];

say.call(red, 'korea', 2, 3); // Number 5 apple(from korea) is good!
say.apply(red, arr) // Number 5 apple(from korea) is good!

 

3. bind

약간 방식이 다른데 결국 똑같음.

let red = {
	fruits: 'apple'
};

const say = function(country, num1, num2) {
	console.log(`Number ${num1 + num2} ${this.fruits}(from ${country}) is good!`);
};

let bound = say.bind(red); // 함수가 만들어짐

bound('korea', 2, 3); // Number 5 apple(from korea) is good!

 

 

 

결론

call, apply, bind 전부 어떤 하나의 method를 갖다 쓰고싶을 때 사용.

(동일한 method를 각 object에 다 넣어버리면 자원낭비니까, 공통으로 쓰이는건 따로 빼서 쓰면 효율적)

 

인자가 여러개일때 call은 일일히 써주고, apply는 array에 넣어서 한번에 써줄 수 있음.

 

bind는 먼저 함수를 하나 리턴 하여 거기에 다시 인자를 써주면 되는 형식.

 

모든 게시물(특히 과거 게시물)은 잘못된 방법으로 처리한것을 좋다고 써놨을 수 있습니다. 참고만 하시고 틀린게 있다면 댓글 남겨주세요~