-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThis&Bind.js
More file actions
75 lines (55 loc) · 1.25 KB
/
This&Bind.js
File metadata and controls
75 lines (55 loc) · 1.25 KB
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
67
68
69
70
71
72
73
74
75
// THIS & BIND
/*
In most cases, the value of "this" is determined
by how a function is called. It can't be set by
assignment during execution, and it may be different
each time the function is called. ES5 introduced
the bind method to set the c=value of a function's "this"
regardless of how it's called. Bind creates a new function
that will have "this" set to the first parameter passed to bind().
*/
let cat = {};
cat = {
sound:'meow',
speak: function(){
console.log(this.sound);
}
};
cat.speak(); //Meow
//
speakFunction = cat.speak;
let speakFunctionBind = speakFunction.bind(cat);
speakFunctionBind();
// Meow
// Review this & bind
// 'this si difined by creation context
// in objects 'this' is set to the object method is called on
// bind
// helps 'this' find context
// pass object as argument to bind method to find desired context
// practice
let person1 = {
name: 'Alex'
};
let person2 = {
name: 'Alexis'
};
function namer() {
return this.name;
}
namer.bind(person1)();
// "Alex"
namer.bind(person2)();
// "Alexis"
//
let number = {
x: 24,
y: 22
};
let count = function() {
console.log(this.x + this.y);
}
count();
let boundFunc = count.bind(number);
boundFunc();
// 46