0

I have many classes that has the following form.

static defaultInstance() {

 if (!defaultInstance) {
   defaultInstance = new Child1()
 }
 return defaultInstance
}

Since they have a common base class, I wanted to add the common function to the base class, but don't know how.
(having trouble with new Child1())

1

1 Answer 1

1

If Child1 is supposed to refer to the "current" class, i.e. the class that defaultInstance is invoked on, then you can just do

defaultInstance = new this();

This follows the normal JavaScript rules: If you invoke the function with Child1.defaultInstance(), then this refers to Child1.

However, this probably doesn't do what you want. If you define defaultInstance on the base class, then all child classes share the same defaultInstance variable.

If you want to have an instance per class, then each class needs its own defaultInstance method, or you need to use a property instead, e.g.

if (!this.__defaultInstance) {
  this.__defaultInstance = new this();
}
Sign up to request clarification or add additional context in comments.

5 Comments

Any reason not to use a Map instead of __defaultInstance? Also that would need to be this.hasOwnProperty('__defaultInstance') or the class inheritance could break it.
You mean a class name -> instance map? That would work too. Or maybe a WeakMap.
e.g. map.set(this, new this());. Good call that WeakMap probably makes more sense, though unless you're dynamically declaring subclasses, the Map will probably be relatively static.
Your description of my problem is very correct, I'm a bit lost on the solution part though, __defaultInstance is a static member variable and each class has its own __defaultInstance ? I guess map variable could live in someplace where all classes can access/share.
"each class has its own __defaultInstance" Yes. "I guess map variable could live in someplace where all classes can access/share." That could just exist in the bas class file.

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.