2

I have many classes and for each class, methods to initialize an instance:

function A() {}
function B() {}

function a(arg) {
  return new A(arg);
}

function b(arg) {
  return new B(arg);
}

I want to have a single function to initialize one of these classes like this:

function any(AorB) {
  return new AorB();
}

How can I do that so the overall code size is small?

eguneys
  • 5,648
  • 7
  • 27
  • 51

1 Answers1

1

If the A and B "classes" are defined at the window-level, you can call the constructor dynamically.

console.log(any('B').name); // '$B'

function A() { this.name = '$A' }
function B() { this.name = '$B' }

function any(AorB) {
  return constructorApply(window[AorB]);
}

function constructorApply(ctor, args) {
  return new (ctor.bind.apply(ctor, [null].concat(args)))();
};
Mr. Polywhirl
  • 35,562
  • 12
  • 75
  • 123