-
Notifications
You must be signed in to change notification settings - Fork 32
/
this.test.js
154 lines (118 loc) · 3.03 KB
/
this.test.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
describe('DAY 7: this keyword', () => {
it(`invoke a constructor function and assign the resulting object to "a"`, () => {
/**
* @returns {undefined|object}
*/
function A () {
this.b = function b () {
return this.c;
};
this.c = [1, 2, 3, 4];
}
// complete the code to pass the test
let a;
expect(a.b()).toBe(a.c);
expect(a).toBeInstanceOf(A);
});
it(`create a bound function to make b return a.c value`, () => {
let a = {
c: [1, 2, 3]
};
/**
* @memberof a
* @returns {array}
*/
function b () {
return this.c;
}
// complete the code to pass the test
let w;
expect(w).toBe(a.c);
});
it(`call function b with a as the belonging object
and provide the required argument values to pass the test`, () => {
let a = {
c: [1, 2, 3]
};
/**
*
* @param {number} x
* @param {number} y
* @memberof a
* @returns {array}
*/
function b (x, y) {
this.x = x;
this.y = y;
return this.c;
}
// complete the code to pass the test
let w;
expect(w).toBe(a.c);
expect(typeof a.x).toBe('number');
expect(typeof a.y).toBe('number');
});
it(`apply a as this for b and pass the required arguments to pass the test`, () => {
let a = {
c: [1, 2, 3]
};
/**
*
* @param {number} x
* @param {number} y
* @memberof a
* @returns {array}
*/
function b (x, y) {
this.x = x;
this.y = y;
return this.c;
}
// complete the code to pass the test
let w;
expect(w).toBe(a.c);
expect(typeof a.x).toBe('number');
expect(typeof a.y).toBe('number');
});
it(`function b should resolve this to object a`, () => {
/**
*
* @memberof a
* @returns {array}
*/
function b () {
return this.c;
}
let a = {
// complete the object property to pass the test
c: [1, 2, 3]
};
expect(a.b).toBe(b);
expect(a.b()).toBe(a.c);
});
it(`lexical this
can you fix it?`, () => {
/**
* @returns {undefined|object}
*/
function A () {
this.b = function () {
// use lexical scope to fix this
return function () {
return this.c;
};
};
this.c = 'hi';
}
let a = new A();
let d = {
b: a.b,
c: 'bye',
e: a.b()
};
let f = a.b();
expect(d.b()()).toBe(d.c);
expect(d.e()).toBe(a.c);
expect(f()).toBe(a.c);
});
});