2

I am trying to create a static method that basically creates an instance of the class that made the call automatically.

In this example, I would like class A to create an instance of itself. How can this be done? The below code gives an error when executed.

class Model {
  static find(someVar) {
    let inst = new this.constructor[this.constructor.name]()
    // Do some extra stuff with the instance
    return inst
  }
}

class A extends Model { }

A.find()

2
  • 3
    let inst = new this(); should work fine: jsfiddle.net/khrismuc/fu3jar8h Commented Aug 7, 2019 at 21:43
  • @ChrisG WOW didn't think it would be that easy... Commented Aug 7, 2019 at 21:43

1 Answer 1

2

Every static method of a class has this context which points to the class after dot

class Model {
  static find(...args) {
    console.log("My name is", this.name) // <- this will print "My name is AModel"
    return new this(...args)
  }
}

class AModel extends Model { }

AModel.find(); // <- passing `this` context to be the AModel class.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.