-
Notifications
You must be signed in to change notification settings - Fork 7
/
bind.ts
62 lines (45 loc) · 1.21 KB
/
bind.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
// * ================================================================================ original
{
const obj = {
val: 'inner',
fn(...args: unknown[]) {
console.warn(...args, this);
},
};
obj.fn('obj call');
const rawFn = obj.fn;
rawFn('raw call');
const bindedFn = obj.fn.bind({ val: 'outer' });
bindedFn('bind1');
const bindedFn2 = bindedFn.bind({ val: 'more' });
bindedFn2('bind2');
}
console.log('--------');
// * ================================================================================ our
{
const bind = <C, T, K>(context: C, fn: (...args: T[]) => K) => {
const sf = Symbol();
Object.defineProperty(context, sf, {
enumerable: false,
configurable: true,
writable: true,
value: fn,
});
const sc: C & { [sf]?: Function } = context;
return (...args: T[]) => sc[sf]?.(...args) as K;
};
// * ----------------
const obj = {
val: 'inner',
fn(...args: unknown[]) {
console.warn(...args, this);
},
};
obj.fn('obj call');
const rawFn = obj.fn;
rawFn('raw call');
const bindedFn = bind({ val: 'outer' }, obj.fn);
bindedFn('bind1');
const bindedFn2 = bind({ val: 'more' }, bindedFn);
bindedFn2('bind2');
}