nico-c
3/1/2017 - 9:54 PM

.bind .call .apply

.bind .call .apply

// Bind lets you attach a function to a different object so that you can control 
// what 'this' refers to, even even if it's not in its lexical scope

// Call lets you call (execute) a function with arguments and allows you to control 
// what 'this' refers to in that function

// Apply does the same thing as call but uses an array of parameters
// CALL
var person = {
  fi: 'Foxi',
  la: 'Di',
  getFullname: function(){
    var fullname = 'Hi, ' + this.fi + ' ' + this.la;
    return fullname;
  }
}

var person2 = {
  fi: 'Riley',
  la: 'Steele'
}

// the 'this' in getFullName refers to person2 here 
var a = person.getFullname.call(person2);
console.log(a) // => Hi, Riley Steele
// CURRYING WITH BIND
function multiply(a,b) {
  return a * b;
}
// the second parameter of the bind will be bound 
//to the 'a' parameter in the multiply function 
var timesTwo = multiply.bind(this, 2)
console.log(timesTwo(2)) // => 4

var timesThree = multiply.bind(this, 3);
console.log(timesThree(2)); // => 6