-
Notifications
You must be signed in to change notification settings - Fork 0
/
this-example2.ts
49 lines (39 loc) · 1.09 KB
/
this-example2.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
class ReferenceClass {
constructor(public message: string) { }
sayHello() {
if (this) {
if ((this as any).document) {
console.log(`Hello window!`)
} else {
console.log(`Hello ${this.message}`);
}
} else {
console.log('Hello [this is undefined]');
}
}
// Invalid
delayedHello() {
setTimeout(this.sayHello, 100);
}
// Valid
instanceFunctionHello() {
setTimeout(() => {
this.sayHello()
}, 120);
}
// Valid
functionBindHello() {
setTimeout(this.sayHello.bind(this), 140);
}
// Always safe
wrappedHello = () => {
this.sayHello();
}
}
new ReferenceClass('Standard').sayHello();
new ReferenceClass('Invalid - window').delayedHello();
new ReferenceClass('Instance Function').instanceFunctionHello();
new ReferenceClass('Function Bind').instanceFunctionHello();
// Straight timeout
setTimeout(new ReferenceClass('Wrapped Delay').wrappedHello, 160);
new ReferenceClass('Wrapped Delay').wrappedHello();