-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.spec.ts
96 lines (88 loc) · 2.29 KB
/
index.spec.ts
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/**
* @jest-environment jsdom
*/
describe('this', function () {
test('做为对象上的方法被调用,方法中的 this 是调用者对象', () => {
const obj1 = {
name: 'Joel',
getName: function () {
return this.name
},
getName2 () {
return this.name
}
}
expect(obj1.getName()).toBe('Joel')
const obj2: Record<string, any> = {
name: 'Jack'
}
obj2.getName = obj1.getName
obj2.getName2 = obj1.getName2
expect(obj2.getName()).toBe('Jack')
expect(obj2.getName2()).toBe('Jack')
})
test('bind 在函数创建时,改变 this 的指向', () => {
const obj1 = {
name: 'Joel',
getName: function () {
return this.name
}
}
const obj2: Record<string, any> = {
name: 'Jack'
}
const obj3 = {
name: 'Mary'
}
obj2.getName = obj1.getName.bind(obj3)
expect(obj2.getName()).toBe('Mary')
})
test('apply, call 在函数调用时,改变 this 的指向', () => {
const obj1 = {
name: 'Joel',
getName: function () {
return this.name
}
}
const obj2: Record<string, any> = {
name: 'Jack'
}
obj2.getName = obj1.getName
expect(obj2.getName()).toBe('Jack')
expect(obj2.getName.call(obj1)).toBe('Joel')
expect(obj2.getName.apply(obj1)).toBe('Joel')
})
test('apply, call 不能改变 bind 过的函数的 this 的指向', () => {
const obj1 = {
name: 'Joel',
getName: function () {
return this.name
}
}
const obj2: Record<string, any> = {
name: 'Jack'
}
obj2.getName = obj1.getName.bind(obj1)
expect(obj2.getName()).toBe('Joel')
// eslint-disable-next-line no-useless-call
expect(obj2.getName.call(obj2)).toBe('Joel')
})
test('箭头函数,this 是最近一层非箭头函数的this', () => {
const obj1 = {
name: 'Joel',
getName: function () {
const arrowGetName = () => this.name
return arrowGetName()
}
}
const obj2: Record<string, any> = {
name: 'Jack'
}
obj2.getName = obj1.getName
expect(obj2.getName()).toBe('Jack')
expect(obj2.getName.call(obj1)).toBe('Joel')
// bind 改不动 this
obj2.getName2 = obj1.getName.bind(obj1)
expect(obj2.getName()).toBe('Jack')
})
})