17. call, apply, bind

적자생존·2022년 7월 4일
0

javascript restart

목록 보기
18/31

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

1. call

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


const mike = {
  name : "Mike"
}
const tom = {
  name : "Tom"
}

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

showName(mike)
// 아무것도 안나옴?
showName.call(mike)
// Mike

그냥 showName(mike)하면 안나오는 이유

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

에서 this가 가르키는 것은 windows이다

그래서 windows.name을 하는 것이고 windows.name은 아무것도 없기 때문에 나오지 않는 것임

call을 붙히게 되면

windows.name이 아니라 call이 const mike를 바인딩하게 되고 this의 범위가 windows에서 const mike로 변하게 되서 windows.name이 아닌 mike.name이 되는 것이다.


const mike = {
  name : "Mike"
}
const tom = {
  name : "Tom"
}

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

update.call(mike, 1999, "singer")
console.log(mike)
// const mike = {
// name : "Mike"
// birthYear : 1999
// occupation : "singer"
// }

call은 인자로 call(바인딩할 대상, 인자, 인자 ...)로 넘겨줄 수 있다.

2. apply

함수 매개변수를 처리하는 방법을 제외하면 call하고 완전히 동일함

apply는 매개변수를 배열로 받음


const mike = {
  name : "Mike"
}
const tom = {
  name : "Tom"
}

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

update.call(mike, [1999, "singer"])
console.log(mike)
// const mike = {
// name : "Mike"
// birthYear : 1999
// occupation : "singer"
// }

매개변수 자체를 배열로 줘야 한다.

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


const num = [1, 7, 52, 82, 3, 6]

const min = Math.min(num)
// NaN
const min = Math.min(...num)
// 1
const min = Math.min.apply(null, num)
// === Math.min.apply(null, [1, 7, 52, 82, 3, 6])
// 1
const min = Math.min.call(null, ...num)
// === Math.min.call(null, 1, 7, 52, 82, 3, 6)
// 1

Math는 따로 this값을 참조하지 않음

3. bind

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


const mike = {
  name : "Mike"
}

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

const updateMike = update.bind(mike)

updateMike(1980, "police")
console.log(mike)
// const mike = {
// name : "Mike"
// birthYear : 1980
// occupation : "police"
// }

예시

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

user.showName()
// hello, Mike

let fn = user.showName
// undefined

변수에 할당하면 this 값을 잃어버리게 된다.


// call 사용

fn.call(user)
// hello, Mike

fn.apply(user)
// hello, Mike

let boundFn= fn.bind(user)

boundFn()
// hello, Mike

즉 bind는 함수에 this 값을 강제로 입력해주는 함수이다.

profile
적는 자만이 생존한다.

0개의 댓글