您需要为每个调用单独存储像r 这样的流值,这对于静态类来说是不合理的目标,因为您一次又一次地使用相同的类,而不是单独的实例。可能的解决方案:
1.不再static:
class A {
room(r) {
this.r = r
return this
}
emit(event, data) {
console.log('this.r', this.r, {event, data})
}
}
new A().room('aa').emit('a1', 'aaa') // r = 'aa'
new A().emit('a2', 'aaa') // r = undefined
2。返回具有自己作用域的实例(A 保持静态):
class A {
static room(r) {
return new B(r)
}
static emit(...args) {
return new B().emit(...args)
}
}
class B {
constructor(r) {
this.r = r
}
emit(event, data) {
console.log('this.r', this.r, {event, data})
return this
}
}
A.room('aa').emit('a1', 'aaa') // r = 'aa'
A.emit('a2', 'aaa') // r = undefined
3.将逻辑委托给非静态类(A 保持静态):
class B {
room(r) {
this.r = r
return this
}
emit(event, data) {
console.log('this.r', this.r, {event, data})
}
}
class A {
static room(...args) {
return new B().room(...args);
}
static emit(...args) {
return new B().emit(...args);
}
}
A.room('aa').emit('a1', 'aaa') // r = 'aa'
A.emit('a2', 'aaa') // r = undefined
...等等。