0

我正在尝试在 NodeJs 之上使用 TypeScript 和 ES6 代理创建一个动态 API。我实现了 API,但经过一些测试后,我发现我超出了堆栈大小。即使我尝试将 --stack-size 设置为 16000 但它仍然超过它!我想我有一些我没有看到的递归方法。

这是我的代码:

export class StackPlate {
public static build(name: string, parent: StackPlate, callback: (type: string, data: any) => any) {
    return (new StackPlate(name, parent, callback)).proxy;
}

private callback: (type: string, data: any) => any;
private parent: StackPlate;
private childs: {[key: string]:  StackPlate} = {};
private name: string = "";
public proxy;

constructor(name: string, parent: StackPlate, callback: (type: string, data: any) => any) {
    this.parent = parent;
    this.name = name;
    this.callback = callback;

    this.proxy = new Proxy((...parameters) => {
        let stack = [this.name];
        let parent = this.parent;
        while(parent) {
            stack.push(parent.getName());
            parent = parent.getParent();
        }
        stack = stack.reverse();
        return this.callback("call", {stack, parameters});
    }, {
        get: (target, property: string): any => {
            if(this.childs[property])
                return this.childs[property].proxy;

            let child = StackPlate.build(property, this, this.callback);
            this.childs[property] = child;

            this.callback("get", {target, property, child});

            return child.proxy;
        },
        set: (target, property: string, value: any, receiver): boolean => {
            let stack = [property, this.name];
            let parent = this.parent;
            while(parent) {
                stack.push(parent.getName());
                parent = parent.getParent();
            }
            stack = stack.reverse();
            return this.callback("set", {stack, property, target, value});
        }
    });
}

public getName() {
    return this.name;
}

public getChilds() {
    return this.childs;
}

public getParent() {
    return this.parent;
}
}

我正在使用 TypeScript 2.4.2 和 Node 8.7.0(也在较低的 8.x 版本上尝试过)。在我的配置中,我将目标设置为 es6。我不明白我的问题是!

PS:测试:

let plate = StackPlate.build("test", undefined, console.log);
plate.a.b.c();  
4

1 回答 1

0

发现问题!在 get 陷阱中,我使用了StackPlate.build实际返回代理的方法,而不是对象本身!这创造了一个循环:)

于 2017-10-22T14:56:32.483 回答