Skip to content

Commit

Permalink
fix: proxy function lost this (#48)
Browse files Browse the repository at this point in the history
Co-authored-by: wanghx <[email protected]>
  • Loading branch information
whxaxes and wanghx authored Aug 9, 2022
1 parent 4679e4d commit 9bba4a6
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 3 deletions.
7 changes: 5 additions & 2 deletions src/lazy_helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,12 @@ function createHandler<T extends Object>(delayedObject: () => T): ProxyHandler<T
const handler: ProxyHandler<T> = {};
const install = (name: keyof ProxyHandler<T>) => {
handler[name] = (...args: any[]) => {
args[0] = delayedObject();
const instance = args[0] = delayedObject();
const method = Reflect[name];
return (method as any)(...args);
const result = (method as any)(...args);
return typeof result === 'function'
? result.bind(instance)
: result;
};
};
reflectMethods.forEach(install);
Expand Down
4 changes: 4 additions & 0 deletions test/container.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import ClassB from './fixtures/value/b';
import LazyCClass from './fixtures/lazy/lazy_c';
import LazyBClass from './fixtures/lazy/lazy_b';
import LazyAClass from './fixtures/lazy/lazy_a';
import LazyDClass from './fixtures/lazy/lazy_d';

const ctx = {};
const container = new Container('default');
Expand Down Expand Up @@ -282,10 +283,13 @@ describe('container#lazy', () => {
const instance = container.get(LazyAClass);
expect(instance).toBeInstanceOf(LazyAClass);
container.set({ type: LazyBClass });
container.set({ type: LazyDClass });
expect(instance.lazyB).toBeDefined();
expect(instance.lazyB).toBeInstanceOf(LazyBClass);
expect(instance.lazyB === instance.lazyB).toBeTruthy();
expect(instance.lazyB.name).toBe('lazyBClass');
expect(instance.lazyB.testLazyD()).toBe('a,b');

container.set({ type: LazyCClass });
const instanceb = container.get(LazyBClass);
expect(instanceb.lazyC).toBeDefined();
Expand Down
12 changes: 11 additions & 1 deletion test/fixtures/lazy/lazy_b.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
import LazyC from './lazy_c';
import LazyD from './lazy_d';
import { Inject, Injectable } from '../../../src';

@Injectable()
export default class LazyBClass {
@Inject({ lazy: true })
lazyC!: LazyC;

@Inject({ lazy: true })
lazyD!: LazyD;

public name = 'lazyBClass';
}

testLazyD() {
this.lazyD.set('a', 'b');
return this.lazyD.doSomething();
}
}
8 changes: 8 additions & 0 deletions test/fixtures/lazy/lazy_d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Injectable } from '../../../src';

@Injectable()
export default class LazyDClass extends Map {
doSomething() {
return Array.from(this.entries()).join(',');
}
}

0 comments on commit 9bba4a6

Please sign in to comment.