this 메서드 - call(), apply(), bind() -

김종인·2022년 10월 26일
post-thumbnail

call

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

const jjong = {
	name: "JJong",
};

const kyukyu = {
	name: "Kyu",
};

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

displayName(); // 아무것도 안뜸 -> this는 window를 가르키며, 이는 빈 문자열 ""을 가르킴.
displayName.call(jjong); // JJong
displayName.call(kyu); // Kyu

update 함수로 보는 예시

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

update.call(jjong, 1997, soccer)
update.call(kyu, 1998, programming)

console.log(jjong); 
console.log(kyukyu); 

apply

apply 메서드 - 함수 매개변수를 처리하는 방법을 제외하면 call과 같다.
call은 일반적인 함수와 마찬가지로 매개 변수를 직접 받지만, apply는 배열로 받는다.

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

update.apply(jjong, [1997, "soccer"]);
console.log(jjong); 

update.apply(kyukyu, [1998, "programming"]);
console.log(kyukyu); 

bind

bind 메서드 - 함수의 this 값을 영구적으로 바꿀 수 있다.

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

const updateJJong = update.bind(jjong);

updateJJong(1997, "soccer");
console.log(jjong);

실제 예제

const user = {
	name: "JJong",
    displayName: function() {
    	console.log(`hello, ${this.name}`);
    },
};

user.displayName();

let fn = user.displayName;

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

let boundFn = fn.bind(user);

boundFn();
profile
성장하는 개발자 JJONG

0개의 댓글