JavaScript: Understanding the Weird Parts - call(), apply(), and bind()
call, apply, bind는 처음 배우는 사람들이 머리를 싸매게 하는 주제이다
함수 수행 컨텍스트와 this 얘기..
메소드는 this를 가지고 this는 객체에 붙어있는 함수이다
함수 수행 컨텍스트를 변형시키는 방법?
call, apply, bind
일단 일급 함수에 대한 이해가 필요하다
함수: 객체의 일종
optional name 속성
code 속성(invocable 관계)
그리고 call, apply, bind 메소드를 가짐
const person = {
firstname: 'John',
lastname: 'Doe',
getFullName: function() {
const fullName = this.firstname + ' ' + this.lastname
return fullName
}
}
const logName = function(lang1, lang2) {
console.log('Logged: ' + this.getFullName())
console.log('Arguments: ' + lang1 + ' ' + lang2)
console.log('--------------')
}
const logFunctionName = logName.bind(person)
logFunctionName('en')
Logged: John Doe
Arguments: en undefined
--------------
bind는 함수를 복사한 새로운 함수 객체를 반환한다
중간에 this를 묶어줌
// call
logName.call(person, 'en', 'es')
// apply
logName.apply(person, ['en', 'es'])
call과 apply는 인자 넣어서 함수 호출
다만 apply는 배열을 쓴다는 점이 차이라고 볼수있다
// function borrowing 테크닉
const person2 = {
firstname: 'Jane',
lastname: 'Doe'
}
person.getFullName.apply(person2)
// bind를 사용한 function currying
function multiply(a, b) {
return a*b
}
const multipleByTwo = multiply.bind(this, 2)
bind를 조금만 응용하면 커링도 쉽게 가능하다
Author And Source
이 문제에 관하여(JavaScript: Understanding the Weird Parts - call(), apply(), and bind()), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@dps0340/JavaScript-Understanding-the-Weird-Parts-call-apply-and-bind저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)