Advertisement
JPDG13

Call, Apply, and Bind, JS

May 4th, 2019
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //  CALL, APPLY, AND BIND
  2.  
  3. var person = {
  4.     firstname: 'Jason',
  5.     lastname: 'DeGraaf',
  6.     getFullName: function() {
  7.         var fullname = this.firstname + ' ' + this.lastname;
  8.         return fullname;
  9.     }
  10. }
  11.  
  12. // bind creates a copy of whatever function you're calling it on.
  13.  
  14. var logName = function(lang1, lang2) {
  15.     console.log('Logged: ' + this.getFullName());
  16.     console.log('Arguments: ' + lang1 + ' ' + lang2);
  17.     console.log('---------------')
  18. }.bind(person);
  19.  
  20. // var logPersonName = logName.bind(person);
  21.  
  22.  
  23. // call actually calls the function.  bind only creates copy
  24. logName('en ', 'es');  //logPersonName();
  25. logName.call(person, 'en', 'es');
  26.  
  27. //appy wants an array!  not a list.  but that's the only difference between call and apply
  28. logName.apply(person, ['en', 'es'])
  29.  
  30.  
  31.  
  32. var person2 = {
  33.     firstname: 'Jane',
  34.     lastname: 'Doe'
  35. }
  36.  
  37. // FUNCTION BORROWING
  38.  
  39. // This crazy set up borrows the 'this' from person object above.
  40. console.log(person.getFullName.apply(person2));
  41.  
  42. // FUNCTION CURRYING
  43. function mutliply(a,b) {
  44.     return a*b;
  45. }
  46. // this bind method permamently sets "a" to 2.  
  47. var multiplyByTwo = mutliply.bind(this, 2);
  48. console.log(multiplyByTwo(4));
  49. //Answer will be 8.  If .bind was (this, 2, 5) set both a permanent. Answer 10.
  50.  
  51. var multiplyByThree = mutliply.bind(this, 3);
  52. console.log(multiplyByThree(4));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement