Search code examples
javascriptstatic-methods

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.
In the two cases below:

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

this is a class 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!


Solution

  • 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. Possible solutions:

    1. No longer 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):

    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):

    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.