CALL(), APPLY() and BIND()

- Controlling the 'this' in when the execution context is created (use call(), apply() and bind())
- A function object has accessed to special function (call, apply, bind) - all has to do with the 'this' variable

var person = {
    firstname: 'John',
    lastname: 'Doe',
    getFullName: function(){
        var fullname = this.firstname + this.lastname; 
        //The method uses the this keyword, since this is a method on an object when this function is 
        //executed the this keyword point to this whole object (person)
        return fullname;
    }
}

var logName = function(lang1, lang2){
    console.log('Logged: ' + this.getFullName)); 
    //this will fail because the this keyword is going to be pointing to the global object, 
    //this function is not a method of the person object 
}

- Would not it be nice if we could control the this keyword (use bind())

var logPersonName = logName.bind(person) 
//Not invoking the function - Using the function as an object and call a method of that object
//Pass in the the object we want to be the 'this' variable (person)
//The bind function returns a new function so it makes a copy of the logName function

logName(); // Does not work
logPersonName(); //Works fine - Execute the copy 

Call: 

logName.call - Calls the function same as logName() but we can control the 'this' variable: logName.call(person, 'en', 'es')

Call vs Bind: Bind creates a copy where Call executes it. 

Apply: 
//Does the same thing as call but wants an array of parameters - 
//can be more useful what if we were adding a bunch of numbers
logName.appy(person, ['en','es']) 

Function borrowing:

We have same properties as person1 except person2 does no have getFullName method:
var person2 = {
    firstname: 'Jane', 
    lastname: 'Doe'
}

person.getFullName.apply(person2); //Setting 'this' to person2 

Function currying:

- Has to do with the bind
- Function currying: Creating a copy of function but with some preset parameters

function multiply(a,b){
    return a*b;
}

var multiplyByTwo = multiply.bind(this, 2) 
//Not executing the function, giving the parameters set the permanent values of these parameters when the copy is made
//equivalent to:
        function multipyByTwo(b){
            var a = 2;
            return a*b;
        }

multipyByTwo(4); = 8 as it is 4*2( 2 was the permanent value)

results matching ""

    No results matching ""