bind()
- 메소드가 호출되면 새로운 함수를 생성
- 받게되는 첫 인자의 value로는 this 키워드를 설정하고, 이어지는 인자들은 바인드된 함수의 인수에 제공
apply()
- 메서드는 주어진 this 값과 배열 (또는 유사 배열 객체) 로 제공되는 arguments 로 함수를 호출
call()
- 메소드는 주어진 this 값 및 각각 전달된 인수와 함께 함수를 호출
:apply()와 call()은 거의 동일하지만, call()은 인수 목록을, 반면에 apply()는 인수 배열을 받는다.
var john = {
name: 'John',
age: 26,
job:'teacher',
presentation: function (style, timeOfDay){
if (style === 'formal'){
console.log('Good ' + timeOfDay + ', Ladies and gentlemen! I\'m '+
this.name + ', I\'m a '+
this.job+ ' and I\'m '+
this.age + ' years old.');
} else if (style === 'friendly'){
console.log('Hey, nice ' + timeOfDay + '. I\'m '+
this.name + ', I\'m a '+
this.job+ ' and I\'m '+
this.age + ' years old.');
}
}
};
var emily = {
name: 'Emily',
age: 35,
job: 'designer'
};
john.presentation('formal','morning');
john.presentation.call(emily,'friendly', 'afternoon');
// using call method borrow john's presentation method
// method borrowing
//john.presentation.apply(emily, ['friendly', 'afternoon']);
// -> this is not worked, cuz presentation method doesn't expect to get an array as input.
//bind는 펑션을 빌려오는게 아니라 복사를 해서 따로 저장할 수 있다.
var johnFriendly = john.presentation.bind(john,'friendly');
johnFriendly('moring');
johnFriendly('night');
// get same printed result
// 같은 문구를 반복하지 않아도 되기 때문에 효율적
var emilyFormal = john.presentation.bind(emily,'formal');
emilyFormal('afternoon');
example
/ bind를 이용하여 나라별 성인 나이를 구하는 예제.
var years = [1990, 1965, 1937, 2005, 1998];
function arrayCalc(arr, fn){
var arrRes = [];
for (var i =0; i<arr.length; i++){
arrRes.push(fn(arr[i]));
}return arrRes;
}
function calculateAge(el){//el===birthDay
return 2016-el;
}
function isFullAge(limit, el){//el===age
return el >= limit;
}
var ages = arrayCalc(years, calculateAge);
var fullJapan = arrayCalc(ages, isFullAge.bind(this, 20));
console.log(ages);
console.log(fullJapan);
'javascript' 카테고리의 다른 글
JavaScript/ let , const & var (0) | 2020.03.09 |
---|---|
JavaScript/ prototype & closure exercise (0) | 2020.03.09 |
JavaScript/ Closure (0) | 2020.02.24 |
JavaScript/ Immediately Invoked Function Expressions [IIFE] (0) | 2020.02.24 |
JavaScript/ First-Class Functions (0) | 2020.02.24 |