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;
return fullname;
}
}
var logName = function(lang1, lang2){
console.log('Logged: ' + this.getFullName));
}
- Would not it be nice if we could control the this keyword (use bind())
var logPersonName = logName.bind(person)
logName();
logPersonName();
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);
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)
function multipyByTwo(b){
var a = 2;
return a*b;
}
multipyByTwo(4); = 8 as it is 4*2( 2 was the permanent value)