-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththisMore.js
More file actions
62 lines (57 loc) · 1.29 KB
/
thisMore.js
File metadata and controls
62 lines (57 loc) · 1.29 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
/*
Note: Run in browser.
*/
const obj = {
name: 'Jack',
sing() {
console.log('a', this); // obj
var fun = function() {
console.log('b' , this); // window
}
fun();
}
}
obj.sing();
console.log('-----------------------');
// Solution 1
const obj1 = {
name: 'Jack',
sing() {
console.log('a', this); // obj1
var fun = () => {
console.log('b' , this); // obj1
}
fun();
}
}
obj1.sing();
console.log('-----------------------');
// Solution 2
const obj2 = {
name: 'Jack',
sing() {
console.log('a', this); // obj2
var fun = function() {
console.log('b' , this); // obj2 (thanks to the binding below)
}
fun.bind(this)();
fun.call(this); // call with the scope/context of this.
fun.apply(this); // call with the scope of this.
}
}
obj2.sing();
console.log('-----------------------');
// Solution 3
const obj4 = {
name: 'Jack',
sing() {
var me = this; // To maintain the scope in inner function.
console.log('a', this); // obj4
var fun = function () {
console.log('b' , this); // Will be window
console.log('use me ', me); // obj4
}
fun();
}
}
obj4.sing();