JavaScript函数分组场景下的别名追踪实现疑问
解决JavaScript函数分组别名的追踪问题
你的核心问题在于当前实现里,some.get()调用时没有关联到对应的别名上下文——所有调用都直接使用同一个some实例,而alias方法只是单纯执行回调,没有记录或传递当前的别名信息。要让get知道自己在哪个别名分组下被调用,需要修改实现,把别名上下文和方法调用绑定起来。
下面提供两种简洁的实现思路:
思路1:用栈追踪当前别名上下文
通过维护一个别名栈,进入alias时将别名压入栈,回调执行完毕后弹出,get方法直接读取栈顶的别名即可关联当前分组。
class SomeClass { constructor() { // 维护别名栈,初始设默认值 this.aliasStack = ['default']; } alias(aliasName, callback) { // 压入当前别名 this.aliasStack.push(aliasName); try { // 执行回调,此时get会读取栈顶的别名 callback(); } finally { // 无论回调是否出错,都弹出当前别名,恢复上下文 this.aliasStack.pop(); } return this; } get(content) { // 取当前栈顶的别名 const currentAlias = this.aliasStack[this.aliasStack.length - 1]; return `${currentAlias}: some${content}`; } } const some = new SomeClass(); some.alias('some', () => { some.alias('anotherSome', () => { console.log(some.get('content')); // 输出: anotherSome: somecontent }); console.log(some.get('contents')); // 输出: some: somecontents some.alias('anotherSomeSome', () => { console.log(some.get('anotherContent')); // 输出: anotherSomeSome: someanotherContent }); });
这种方式不需要修改回调写法,依然可以直接用some实例调用方法,栈会自动维护当前的别名上下文。
思路2:返回绑定别名的实例
让alias方法返回一个绑定了当前别名的新实例,回调里使用这个实例调用get,直接把别名和方法调用绑定。
class SomeClass { constructor(currentAlias = 'default') { this.currentAlias = currentAlias; } alias(aliasName, callback) { // 创建新的实例,绑定当前别名 const aliasedInstance = new SomeClass(aliasName); // 回调里使用这个新实例 callback(aliasedInstance); return this; } get(content) { return `${this.currentAlias}: some${content}`; } } const some = new SomeClass(); some.alias('some', (someInstance) => { someInstance.alias('anotherSome', (anotherInstance) => { console.log(anotherInstance.get('content')); // 输出: anotherSome: somecontent }); console.log(someInstance.get('contents')); // 输出: some: somecontents someInstance.alias('anotherSomeSome', (anotherSomeInstance) => { console.log(anotherSomeInstance.get('anotherContent')); // 输出: anotherSomeSome: someanotherContent }); });
这种方式更直观,每个别名分组都有对应的实例,回调里通过参数拿到该实例,调用get时自然关联对应的别名。
内容的提问来源于stack exchange,提问作者simon
相关产品推荐
相关产品推荐

