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

eugene
  • 39,839
  • 68
  • 255
  • 489
  • have you tried looking at this answer? http://stackoverflow.com/questions/27642239/what-is-polymorphism-in-javascript – Train Oct 27 '16 at 03:17

1 Answers1

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();
}
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 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. – loganfsmyth Oct 27 '16 at 05:31
  • You mean a `class name -> instance` map? That would work too. Or maybe a `WeakMap`. – Felix Kling Oct 27 '16 at 06:07
  • 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. – loganfsmyth Oct 27 '16 at 06:22
  • 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. – eugene Oct 27 '16 at 07:46
  • 1
    *"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. – Felix Kling Oct 27 '16 at 07:49