"new self ()" equivalent in Javascript

I have a class like the following:

const Module = {
  Example: class {
    constructor(a) {
      this.a = a;
    }

    static fromString(s) {
      // parsing code
      return new Module.Example(a);
    }
  }
}

This still works, but accessing the current class constructor using a global name Module.Exampleis pretty ugly and prone to cracking.

In PHP, I would use new self()either new static()here to refer to the class in which the static method is installed. Is there something similar in Javascript that is independent of the global scope?

+8
source share
1 answer

You can just use thisinside the static method. It will refer to the class itself, not the instance, so you can just instantiate it from there.

, this.constructor, .

:

const Module = {
  Example: class Example {
    constructor(a) {
      this.a = a;
    }

    static fromString(s) {
      // parsing code
      return new this(s);
    }

    copy() {
      return new this.constructor(this.a);
    }
  }
}

const mod = Module.Example.fromString('my str');
console.log(mod) // => { "a": "my str" 
console.log(mod.copy()) // => { "a": "my str" }
console.log('eq 1', mod === mod) // => true
console.log('eq 2', mod === mod.copy()) // => false
Hide result

+16

Source: https://habr.com/ru/post/1679616/


All Articles