Call, Apply, and Bind Methods

Video

JavaScript Notes

JavaScript
    // the difference between call ( ), apply ( ), and bind ( )
    // without strict mode “this” will default to the Global/Window obj
    // ‘use strict’;
    
    let bob = function(num, str){
          console.log('bob', num, str, this);
          return true;
    }
    
    let bill = {
         name: 'Bill Murray',
         movie: 'Lost in Translation', 
         myMethod: function(fn){		//callback function
                // fn(2, ‘hello’);
                // even though not defined as parameters to the function, can still retrieve extra parameters using the arguments function
                let n = arguments[1];   
                let s = arguments[2];
                fn.apply(bill, [n, s]);
         }
    }
    
    bob.call(bill, 2, 'goodbye');	// when this is returned, it the function context will refer to the object bill
    let arr = [3, 'hi'];
    bob.apply(bill, arr);			// with apply, the 2nd argument accepts an array of parameters, unlike call
    
    bill.myMethod(bob, 4, 'ciao');
    
    let fred = bob.bind(bill, 5, 'hasta la vista' );	// bind returns a copy of the function
    fred ( );