[Javascript] Closure, Bind, Apply

Closure

An inner function has always access to the variables and parameters of its outer function, even after the outer function has returned.

1
2
3
4
5
6
7
8
9
10
function retirement(retirementAge) {
var a = ' years left until retirement';
return function(yearOfBirth) {
var age = 2016 - yearOfBirth;
console.log((retirementAge - age) + a);
}
}

var retirementUS = retirement(66);
retirementUS(1990);

Bind, Call and Apply

call and apply basically are used to define the execution context of the current method.

The difference between bind and call is that bind will return a function reference that can be used later, but call will only return the result from the immediate execution of the function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var john = {
name: 'John',
age: 26,
job: 'teacher',
presentation: function(style, timeOfDay) {
if (style === 'formal') {
console.log('Good ' + timeOfDay + ', Ladies I\'m ' + this.name );
} else if (style === 'friendly') {
console.log('Hey what\'s up!');
}
}
}

var emily = {
name: 'Emily',
age: 35,
job: 'designer'
};

john.presentation('formal', 'morning');
john.presentation.call(emily, 'formal', 'morning'); // Call reset the 'this' keyword to the current object
john.presentation.apply(emipy, ['friendly', 'morning']) // Same to call but when the parameter is an array

var johnFriendly = john.presentation.bind(john, 'friendly'); // Create a copy of the function, has this keyword set to the provided value, and with preset arguments
johnFriendly('morning');

this keyword

In ES5

this keyword refers to the object it belongs to.

  • In a method, this refers to the owner object
  • Alone, this refers to the global object
  • In a function, this refers to the global object
  • In a function, in strict mode, this is undefined
  • In an event, this refers to the element that received the event
  • Methods like call(), and apply() can refer this to any object
1
2
3
4
5
6
7
8
9
10
11
var box5 = {
color: 'green',
position: 1,
clickMe: function() {
var self = this;
document.querySelector('.green').addEventListener('click', function() {
var str = 'This is box number ' + self.position + ' and it is ' + self.color;
})
}
}
box5.clickMe();

In ES6

1
2
3
4
5
6
7
8
9
const box6 = {
color: 'green',
position: 1,
clickMe: function() {
document.querySelector('.green').addEventListener('click', () => {
var str = 'This is box number ' + this.position + ' and it is ' + this.color;
})
}
}