-
Notifications
You must be signed in to change notification settings - Fork 47
/
bind-call-apply.js
62 lines (50 loc) · 1.45 KB
/
bind-call-apply.js
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//first example
var john = {
name: 'John',
age: 26,
job: 'teacher',
//you can add function on object
presentation: function(style, timeOfDay) {
if (style === 'formal') {
console.log('Good ' + timeOfDay + ', Ladies and gentlemen! I\'m ' + this.name + ', I\'m a ' + this.job + ' and I\'m ' + this.age + ' years old.');
} else if (style === 'friendly') {
console.log('Hey! What\'s up? I\'m ' + this.name + ', I\'m a ' + this.job + ' and I\'m ' + this.age + ' years old. Have a nice ' + timeOfDay + '.');
}
}
};
//there is objet here
var emily = {
name: 'Emily',
age: 35,
job: 'designer'
};
//apply
john.presentation('formal', 'morning');
//call
john.presentation.call(emily, 'friendly', 'afternoon');
//bind
var johnFriendly = john.presentation.bind(john, 'friendly');
johnFriendly('morning');
johnFriendly('night');
//bind
var emilyFormal = john.presentation.bind(emily, 'formal');
emilyFormal('afternoon');
// Another cool example
var years = [1990, 1965, 1937, 2005, 1998];
function arrayCalc(arr, fn) {
var arrRes = [];
for (var i = 0; i < arr.length; i++) {
arrRes.push(fn(arr[i]));
}
return arrRes;
}
function calculateAge(el) {
return 2016 - el;
}
function isFullAge(limit, el) {
return el >= limit;
}
var ages = arrayCalc(years, calculateAge);
var fullJapan = arrayCalc(ages, isFullAge.bind(this, 20));
console.log(ages);
console.log(fullJapan);