-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path08_BindCallApply.js
76 lines (49 loc) · 2.12 KB
/
08_BindCallApply.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
63
64
65
66
/*-----------------------------------------------------------------------------*/
/* Bind, Call, and Apply are methods which are used to transfer a function to
// an object (while also transferring this context).
-------------------------------------------------------------------------------*/
// NOTE a JavaScript function in reality is an object.
const club1 = {
club: "Manchester",
num: 7,
player: function (name) {
console.log(`${this.club}'s player, ${name}, number ${this.num}.`);
}
}
const club2 = {
club: "Madrid",
num: 9
}
/*-----------------------------------------------------------------------------*/
/* Bind
-------------------------------------------------------------------------------*/
// club1.player.bind(club2, "Ronaldo")()
const transfer = club1.player.bind(club2, "Ronaldo")
transfer()
console.log(club2); // club2 doesn't actually have the "player" method
/*-----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------*/
/* Call
-------------------------------------------------------------------------------*/
// Differences:
// 1. Executes the function it was called upon right away.
// 2. The call() method does not make a copy of the function it is being called on. (!!!)
club1.player.call(club2, "Ronaldo")
/*-----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------*/
/* Apply is exact same as call
-------------------------------------------------------------------------------*/
// Differences:
// 1. Expects an array of parameters.
club1.player.apply(club2, ["Ronaldo"])
/*-----------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------*/
/* Passing a function to an object
-------------------------------------------------------------------------------*/
const myself = {
name: "Dimon"
}
function me() {
console.log(`My name is ${this.name}.`);
}
me.bind(myself)()