5

In PHP a string can be used to dynamically select a class for instantiation. Here are 2 simple classes in PHP:

<?php
class Magic implements Genius {
  public function perform() {
    echo 'madya look :P' . PHP_EOL;
  }
}

class Genie implements Genius {
  public function perform() {
    echo 'your wish has been granted!' . PHP_EOL;
  }
}

Now there could be a variable such that the class instantiated at runtime is based upon its contents

$sGeniusClass = 'Magic';
$oGenius      = new $sGeniusClass();

Now in Javascript I like to use functions as constructors to have some level of typed-ness, in that vein I might have:

function Magic() {}
Magic.prototype = {
  perform : function()
  {
    console.log('madya look :P');
  }
}

function Genie() {}
Genie.prototype = {
  perform : function()
  {
    console.log('your wish has been granted!');
  }
}

I know I can pull off something similar to PHP with an eval:

Approach #1

var sClassName = 'Genie';
eval('var oGenius = new ' + sClassName);

I've also seen an approach that makes a call to the Function function:

Approach #2

var sClassName = 'Genie';
var oGenius = new Function('return new ' + sClassName)();

On the MDN though it sounds like this suffers performance from re-evaluation every time an instance is created:

Function objects created with the Function constructor are parsed when the function is created. This is less efficient than declaring a function and calling it within your code, because functions declared with the function statement are parsed with the rest of the code.

Now I have one more approach that is a bit tedious:

Approach #3

var aClassMap = {
  Magic : Magic,
  Genie : Genie,
  create : function(sClassName) {
    if(this[sClassName] === undefined)
      return false;
    return new this[sClassName];
  }
}

var sClassName = 'Genie';
var oGenius = aClassMap.create(sClassName);

It seems to be my favorite overall, no use of eval, and no subsequent re-evaluation, like solution #2. It's still a bit of work though, so my question, twofold:

  1. Are there any other ways to do this other than the 3 approaches I've shown?
  2. Is there something similar to PHP where a string can map to a function to be instantiated?
2
  • How to use approach #2 with passing arguments to the new function? So it will be executed like: new Genie('foo') With foo also being a variable?
    – seymar
    Jun 28, 2013 at 20:47
  • Found it! It goes like this: var oGenius = new Function('arg1', 'return new ' + sClassName + '(arg1)')($argumentVariable);
    – seymar
    Jun 28, 2013 at 21:02

1 Answer 1

4

I think you covered them all. You can simplify your 3rd approach, however, by remembering that global variables and functions are properties of the window object, so you can create global classes using window, like this:

var myClassName = "Genie";
window[myClassName] = function {};
window[myClassName].prototype = {
  perform : function()
  {
    console.log('I am a ' + myClassName + ', and your wish has been granted!');
  }
}

I think performance will be as good as always (since Javascript uses hash tables internally to reference object properties, no matter what).

3
  • Definitely looks like a reasonable approach with the only drawback being the classes may not be portable to other environments like node.js. However I made no mention of that in the question :) Feb 10, 2012 at 3:23
  • You don't actually have to modify the way you declare your types. You can still just write function Genie(){}, then create an instance with var o = new window["Genie"]();
    – SynXsiS
    Feb 10, 2012 at 3:39
  • Ah @SynXsiS, that's a great tip and about the cleanest thing I've seen, thx. Feb 10, 2012 at 3:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.