JavaScript方法链场景下:如何限制方法调用顺序与重复调用?
针对两个调用限制问题的解决方案
1. 禁止在调用defineX前执行add方法
核心思路是给类添加一个初始化状态标记,在add和value方法执行前先校验这个标记:只有调用过defineX完成初始化后,才允许执行后续方法。
修改后的代码:
class cl { #x; #initialized = false; // 私有状态标记,记录是否完成初始化 defineX(n) { this.#x = n; this.#initialized = true; return this; } add(n) { if (!this.#initialized) { throw new Error('请先调用defineX完成初始化,再调用add方法'); } this.#x += n; return this; } value() { if (!this.#initialized) { throw new Error('请先调用defineX完成初始化,再获取值'); } return this.#x; } } const cObj = new cl(); console.log(cObj.defineX(3).add(5).value()); // 输出 8 // cObj.add(3) // 执行此行会抛出错误,符合预期
2. 禁止add方法被多次调用
在上述基础上,再添加一个add调用状态标记,每次执行add前先检查这个标记:如果已经调用过一次,就阻止后续调用。
最终整合代码:
class cl { #x; #initialized = false; #addCalled = false; // 私有标记,记录add是否已被调用过 defineX(n) { this.#x = n; this.#initialized = true; return this; } add(n) { if (!this.#initialized) { throw new Error('请先调用defineX完成初始化,再调用add方法'); } if (this.#addCalled) { throw new Error('add方法只能调用一次'); } this.#x += n; this.#addCalled = true; return this; } value() { if (!this.#initialized) { throw new Error('请先调用defineX完成初始化,再获取值'); } return this.#x; } } const cObj = new cl(); console.log(cObj.defineX(3).add(5).value()); // 输出 8 // cObj.add(3) // 首次调用add后再执行此行会抛出错误 // cObj.defineX(2).add(1).add(2) // 第二次调用add同样会抛出错误
可选优化
如果不想抛出错误(比如希望静默忽略非法调用),可以把throw语句改成直接return this,这样不会中断程序,但也不会执行非法的逻辑。比如:
add(n) { if (!this.#initialized || this.#addCalled) { return this; } this.#x += n; this.#addCalled = true; return this; }
内容的提问来源于stack exchange,提问作者aziz
相关产品推荐
相关产品推荐

