본문 바로가기
Frontend/JavaScript

[JS] 8강 자바스크립트 "bind","call","apply"

by 잉나영 2025. 3. 28.
728x90
반응형

1. Call() 메소드

함수를 호출하는 함수

매개변수로 어떠한 것을 전달해주면 호출되는 함수의 this안에 window 객체가 아닌 전달받은 것을 받게 됨

 

// Call();
const fullName = function(city, country) {
    console.log(this.firstName + ' ' + this.lastName , city , country);
}

const person1 = {
    firstName: 'John',
    lastName: 'Smith'
}

fullName.call(person1, "Oslo","Norway");

 

2. Apply() 메소드

call 메서드와 비슷하지만 인수 부분을 배열로 넣어줘야 함

// Apply()
const fullName = function(city, country) {
    console.log(this.firstName + ' ' + this.lastName , city , country);
}

const person1 = {
    firstName: 'John',
    lastName: 'Smith'
}

fullName.apply(person1,["Oslo","Norway"]);

 

3. Bind() 메소드

call, apply와 다르게 직접 함수를 실행하지 않고 반환

this가 window 객체 대신 다른게 나오게 할 수 있음

// Bind()
function func(language) {
    if(language === 'kor') {
        console.log(`language: ${this.korGreeting}`);
    } else {
        console.log(`language: ${this.engGreeting}`);
    }
}

const greeting = {
    korGreeting: '안녕',
    engGreeting: 'Hello',
}

const boundFunc = func.bind(greeting);
boundFunc('kor');

 

728x90
반응형