在 javascript 中将函数分组在一起

问题描述 投票:0回答:1

我正在尝试在 javascript 中将函数分组在一起,尽管我在理解如何跟踪这些组方面有一些困难。在下面的示例中,我的问题是:“some.get('anotherContent')”如何知道它是在别名“anotherSomeSome”而不是“anotherSome”下查询的 - 我的意思是,如何跟踪不同的内容该模型中的别名?下面是我尝试过的,但我发现它非常复杂并且很难跟踪别名:

class someClass {
    alias(callback) {
        callback();
        return this;
    }

    get(content) {
        return 'some' + content;
    }
}

const some = new someClass();

some.alias('some', () => {
    some.alias('anotherSome', () => {
        some.get('content')
    })
    
    some.get('contents')

    some.alias('anotherSomeSome', () {
        some.get('anotherContent')
    })
})
javascript chaining
1个回答
0
投票

从表面上看,它看起来像是一个 XY 问题......无论如何。

一种简单的方法是参数钻取,因此您可以将别名与参数一起传递到堆栈中。

如果您的代码同步,您可以将别名保存在类属性中。就我而言,我将其保存在

path
数组中,这样整个堆栈都是可追踪的。

class someClass {
    path = [];
    alias(alias, callback) {
        this.path.push(alias);
        callback();
        this.path.pop();
        return this;
    }

    get(content) {
        console.log(this.path.join(' / '), 'some' + content);
    }
}

const some = new someClass();

some.alias('some', () => {
    some.alias('anotherSome', () => {
        some.get('content')
    })
    
    some.get('contents')

    some.alias('anotherSomeSome', () => {
        some.get('anotherContent')
    })
})

一旦引入异步(可能更复杂)代码,您就需要跟踪您的调用。 我发现使用返回具有单独路径的

some
实例的代理很有趣(可能是某种设计模式):

class someClass {
    path = [];
    alias(alias, callback) {
        callback(new Proxy(this, {
          get(self, prop){
            if(prop === 'path'){
              return [...self.path, alias];
            }
            return Reflect.get(...arguments);
          }
        }));
        return this;
    }

    get(content) {
        console.log(this.path.join(' / '), 'some' + content);
    }
}

const some = new someClass();

some.alias('some', some => {
    some.alias('anotherSome', some => {
        some.get('content')
    })
    
    some.get('contents')

    some.alias('anotherSomeSome', some => {
        some.get('anotherContent')
    })
})

© www.soinside.com 2019 - 2024. All rights reserved.