프로그래밍/JavaScript

[JS] call, apply, bind

L.Joey 2024. 3. 6. 12:43

 

call, apply, bind ??

  • call : call 메서드는 모든 함수에서 사용할 수 있으며, this 를 특정값으로 지정할수 있습니다.
    매개변수를 직접받는다.
const joey = {
  name: "Joey"
}

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

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

showName.call(joey) // Joey
updateInformation.call(joey, 1987, "developer")
console.log(joey) // {name: "Joey", birthYear: 1987, occupation: "developer"}

 

  • apply : apply 는 함수 매개변수를 배열로 받는 다는 점을 제외하면 call 과 완전히 같은 메서드입니다.
const joey = {
  name: "Joey"
}

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

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

showName.apply(joey) // Joey
updateInformation.apply(joey, [1987, "developer"]) // <<< 배열로 변경
console.log(joey) // {name: "Joey", birthYear: 1987, occupation: "developer"}


// 다른예제

const nums = [6,4,10,1]
const minNum = Math.min(...nums); // 1

const minNum2 = Math.min.apply(null, nums); // 1
// = Math.min.apply(null, [6,4,10,1]);

const minNum3 = Math.min.call(null, ...nums); // 1
// = Math.min.apply(null, 6,4,10,1);

 

  • bind : 함수의 this 값을 영구히 바꿀 수 있습니다.
const user = {
  name: "Joey",
  showName : function(){
    console.log(`Hello, ${this.name}`)
  },
}

user.showName(); // "Hello, Joey" 

let fn = user.showName; // fn 에 할당할 때 this 를 잃어버린다.
//fn(); // "Hello, "

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

let bindFn = fn.bind(user);
bindFn()