eugene
eugene

Reputation: 41735

javascript, polymorphic new Myclass()?

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

Upvotes: 0

Views: 48

Answers (1)

Felix Kling
Felix Kling

Reputation: 816840

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

Upvotes: 1

Related Questions