Skip to content
Advertisement

JavaScript – using named constructors

I have been using dart OOP a lot lately and there we used to have named constructors like DateTime.now().

How do we use the same functionality in JavaScript, with a default constructor and other named constructors for the class ?

Advertisement

Answer

You could do this like this:

class MultiConstructor {
   constructor() {
      // default constructor
   }

   //...other methods
}

MultiConstructor.now = function() {
  const res = new MultiConstructor()
  // configure object
  return res
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement