4월 13일(수) 자바스크립트 call, apply, bind

Southbig·2022년 4월 13일
0

자바스크립트 call, apply, bind

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

call

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

const mike = {
	name: 'Mike',
}

const tom = {
	name: 'Tom'
}

function showThisName() {
	console.log(this.name) // this는 window를 가르키기 때문에 아무것도 뜨지 않는다
}

showThisName(); // 아무것도 뜨지 않는다
showThisName.call(mike); // this 지정

함수로 호출하면서 call을 사용하면서 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;
}

undate.call(this로 사용할 아이, 매개변수1, 매개변수2)
undate.call(mike, 1999, 'singer')

console.log(mike)
// mike = {name: Mike, birthYear: 1999, occupation: 'singer'}

첫번째 매개변수는 this로 사용할 값
두번째부터의 매개변수는 update에서 사용할 매개변수들을 순서대로 적용하여
mike 변수에 update 적용

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;
}

undate.call(this로 사용할 아이, [매개변수1, 매개변수2])
undate.call(mike, [1999, 'singer'])

console.log(mike)
// mike = {name: Mike, birthYear: 1999, occupation: 'singer'}

apply는 배열요소를 함수 매개변수로 사용할때 유용하다

apply는 두번째 매개변수로 배열을 전달하면 그 요소들을 차례대로 인수로 사용한다

const nums = [3, 10, 1, 6, 4];

const minNum = Math.min.apply(null, nums); // Math.min나 Math.max는 this가 필요하지 않아서 null 값을 줬다, 아무값이나 넣어도 상관없다
const maxNum = Math.max.apply(null, nums);

console.log(minNum);
console.log(maxNum);

bind

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

const mike = {
	name: 'Mike',
}


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

항상 this값을 mike값으로 지정하려면 bind를 사용하면 된다.

const updateMike = update.bind(mike); // 항상 mike를 this로 받는다

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

user.showName(); // hello, Mike

let fn = user.showName; 
fn() // hello // fn을 할당할때 this를 잃어버림

user.showName();에서 메소드는 점앞에있는 user가 this다

fn() 이렇게만 호출하여 this를 잃어 버린것이다

const user = {
	name: 'Mike',
	showName: function() {
    	console.log(`hello, ${this.name}`)
	}
}

user.showName(); // hello, Mike

let fn = user.showName; 
fn.call(user) // hello, Mike // call을 사용하여 this값을 넣어주면 this값을 잃어 버리지않는다
fn.apply(user) // 동일

bind로 this값 지정

const user = {
	name: 'Mike',
	showName: function() {
    	console.log(`hello, ${this.name}`)
	}
}

user.showName(); // hello, Mike

let fn = user.showName; 

let boundFn = fn.bind(user);

boundFn() // hello, Mike // this 값을 bind로 지정했기 때문에 동일한 값을 받을 수 있다
profile
즐겁게 살자

0개의 댓글