14

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 works so far, but accessing the current class constructor via the global name Module.Example is kind of ugly and prone to breaking.

In PHP, I would use new self() or new static() here to reference the class that the static method is defined in. Is there something like this in Javascript that doesn't depend on the global scope?

1
  • 2
    I would learn how prototype work first, as the "class" you're creating is already an object. Commented Jun 19, 2017 at 10:14

1 Answer 1

35

You can just use this inside the static method. It will refer to the class itself instead of an instance, so you can just instantiate it from there.

If you need to access the constructor from an instance function, you can use this.constructor to get the constructor without specifying its name.

Here's how:

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

4
  • Is there a way to do it from a non-static method?
    – orrd
    Commented Sep 9, 2019 at 4:17
  • 1
    @orrd you can use this.constructor, and pass the required arguments (e.g. return new this.constructor('newStr');. I've updated the answer to include an example
    – casraf
    Commented Sep 9, 2019 at 13:30
  • doesn't seem to work in all cases... this seems to be undefined if the static method is used inside a map? Commented Jun 28, 2020 at 2:00
  • 1
    @igorsantos07 try saving it first under a different name, e.g. let thisBackup = this; then inside your map (or similar) function, manipulate thisBackup instead.
    – Berbare
    Commented Jul 7, 2020 at 19:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.