-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathcall.ts
48 lines (37 loc) · 937 Bytes
/
call.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
// * ================================================================================ original
{
const obj = {
val: 'inner',
fn(...args: unknown[]) {
console.warn(...args, this);
},
};
obj.fn(333);
obj.fn.call({ val: 'outer' }, 666);
}
console.log('--------');
// * ================================================================================ our
{
const call = <C, T>(context: C, fn: Function, ...args: T[]) => {
const sf = Symbol();
Object.defineProperty(context, sf, {
enumerable: false,
configurable: true,
writable: true,
value: fn,
});
const sc: C & { [sf]?: Function } = context;
const result = sc[sf]?.(...args);
delete sc[sf];
return result;
};
// * ----------------
const obj = {
val: 'inner',
fn(...args: any[]) {
console.warn(...args, this);
},
};
obj.fn(333);
call({ val: 'outer' }, obj.fn, 666);
}