-
call, apply, bindjavascript 2020. 5. 28. 20:05
//Bind, call and 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! What\'s up? I\'m '+ this.name + ', I\'m a ' + this.job + ' and I\'m ' + this.age + ' years old. Have a nice ' + timeOfDay + '.'); } } }; var emily = { name : 'Emily', age : 35, job : 'designer' }; john.presentation('formal','morning'); john.presentation.call(emily, 'friendly', 'afternoon'); // john.presentation.apply(emily, ['friendly','afternoon']); var johnFriendly = john.presentation.bind(john, 'friendly'); johnFriendly('morning'); johnFriendly('night'); var emilyFormal = john.presentation.bind(emily, 'formal'); emilyFormal('afternoon'); var years = [1999, 1980, 2012, 1983, 1933]; function arrayCalc(arr, fn){ var arrRes = []; for(var i = 0; i < arr.length ; i++){ arrRes.push(fn(arr[i])); } return arrRes; } function claculateAge(el) { return 2016 - el; } function isFUllAge(limit, el){ return el >= limit; } var ages = arrayCalc(years, claculateAge); var fullJapan = arrayCalc(ages, isFUllAge.bind(this, 20)); /* 여기서 this는 arrayCalc를 의미한다. 따라서 isFUllAge.bind(this, 20)는 function isFUllAge(limit, el){ return el >= limit; } 여기서 function isFUllAge(20, el){ return el >= limit; } 까지를 의미하는 함수가 되고 남은 el 아규먼트는 function arrayCalc(arr, fn){ var arrRes = []; for(var i = 0; i < arr.length ; i++){ arrRes.push(fn(arr[i])); } return arrRes; } 가 function arrayCalc(arr, fn){ var arrRes = []; for(var i = 0; i < arr.length ; i++){ arrRes.push(function isFUllAge(20, (arr[i])){ return el >= limit; }); } return arrRes; } 이렇게 실행되는 것이다. */ console.log(ages); console.log(fullJapan);
참조 : Udemy - The Complete JavaScript Course 2020 : Build Real Projects!
https://wooooooak.github.io/javascript/2018/12/08/call,apply,bind/
'javascript' 카테고리의 다른 글
Function Statements(Declarations) and Expressions (0) 2020.10.10 forEach에 대해서 참조한 블로그 + 여러가지 배열 메소드 (0) 2020.06.06 closure (0) 2020.05.28 function (0) 2020.05.28 Creating Object (0) 2020.05.27