moringaman
3/26/2017 - 3:44 PM

Call() apply() and bind()

Call() apply() and bind()

// create person object with getFullname function inside
var person = {

  firstname: "joe",
  lastname: "Smith",
  
  getFullName: function(){
    
    var fullname = this.firstname + ' ' + this.lastname;
    return fullname;
  }
}

//create external object equal to function logging the result of
//getFullName
var logName = function(lang1, lang2){
     console.log("logged " + this.getFullName());
     console.log('arguments: ' + lang1 + ' ' + lang2);
    console.log("-----------------")
}

//create a new instance of function logName as personName, binding
//this to the person object 
var personName = logName.bind(person);

//Envoke personName passing your parameters
personName("en", "es");

// Or - User call to envoke logName binding this to person with params
logName.call(person, "en", "es");

// Or use apply to do the same but passing an array of params
logName.apply(person, ["en", "es"]);

//Use an iffie and bind this to person with params 
(function(lang1, lang2){
     console.log("IFFIE logged " + this.getFullName());
     console.log('arguments: ' + lang1 + ' ' + lang2);
    console.log("-----------------")
}).apply(person, ["en", "es"])

//function borrowing to run function inside one object on another
var person2 = {
  
  firstname: "billy",
  lastname: "piper"
}

console.log(person.getFullName.call(person2));