this 지정

김수민·2023년 2월 16일

JavaScript

목록 보기
25/27

call(this로 지정할 대상)

함수 호출에서 사용할 this를 지정한다.

	const green={name:"green",age:30}
	const blue={name:"blue",age:30}
	function showName(){console.log(this.name);}
	
	showName() //this=> window
	showName.call(green) //this=> green
	showName.call(blue) //this=> blue

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

매개변수와 같이 사용하고 싶을 때에는

	const green={name:"green",age:30}
	function update(birth, job){
		this.birth= birth;
		this.job= job;
	}
	update.call(green,1998,"teacher");

와 같이 (call의 this로 지정되는 값, 매개변수, 매개변수)로 입력한다.

위의 green은 이런 모양이 된다.

apply(this로 지정할 대상)

함수 배개변수를 처리하는 방법을 제외하면 call과 동일한 효과를 낸다.
call=> 일반적인 함수와 같이 매개변수를 직접 받음
apply=> 배열로 받음
매개변수와 같이 사용하고 싶을 때에는

	const green={name:"green",age:30}
	function update(birth, job){
		this.birth= birth;
		this.job= job;
	}
	update.apply(green,[1998,"teacher"]);

와 같이 (apply의 this로 지정되는 값, [매개변수, 매개변수])로 입력한다.

	const numArr=[1,2,3,4]
    const min= Math.min.call(null, ...numArr);
	const min= Math.min.apply(null, numArr);

💡 값을 배열로 받으면, call에서는 나머지 매개변수로 펼쳐줘야하지만, apply에서는 그대로 사용할 수 있다.

bind(this로 지정할 대상)

함수에서 사용할 this를 영구적으로 지정한다.

생성👉 const 변수명A=함수명B.bind(this의 대상C)
실행👉 변수명A(함수명B의 매개변수로 들어갈 값);

	function update(birth, job){
		this.birth= birth;
		this.job= job;
	}

	const bella={name:"bella", age:30};
	const updatebella= update.bind(bella);
	updatebella(1999,"police");

위에서 updatebella는 bind된 함수 update를 bella만을 대상으로 실행하는 함수이다.
위의 bella는 아래와 같은 모습이 된다.

요약

const user={
 name: "bella",
 showName: function(){
   console.log(`hello, ${this.name}`);
  }
}
user.showName();
let fn= user.showName;

을 하고자 할 때,

Call

fn.call(user);

apply

fn.apply(user);

bind

let bindFun= fn.bind(user);
bindFun();
profile
sumin0gig

0개의 댓글