简体   繁体   English

javascript静态类检测哪个方法调用以前

[英]javascript static class detect which method call previous

could you help me!你可以帮帮我吗! In the emit method how to check they call room method previous or not.emit方法中如何检查他们之前是否调用了room方法。
In the two cases below:在以下两种情况下:

// case 1: A.room('aa').emit('a1', 'aaa')
// case 2: A.emit('a2', 'aaa')

this is a class A这是A

class A {
  static room(r) {
    this.r = r
    return this
  }
  static emit(event, data) {
    //todo
    console.log('this.r', this.r, {event, data})
  }
}

Thank for your time!感谢您的时间!

You need to store flow values like r separately for each call, which is not reasonable aim for static classes because you use same same class again and again, instead of separate instanses.您需要为每个调用单独存储流值,例如r ,这对于静态类来说不是合理的目标,因为您一次又一次地使用相同的类,而不是单独的实例。 Possible solutions:可能的解决方案:

1. No longer static : 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. Return instances with own scopes ( A keeps static): 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. Delegate logic to non-static class ( A keeps static): 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

... and so on. ... 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM