An instance of a new Javascript object from a dynamic function name

In PHP, a string can be used to dynamically select a class to instantiate. 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 may be a variable such that the class created at runtime is based on its contents

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

Now in Javascript, I like to use functions as constructors to have some level of typing, in the sense that I can 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 that I can hide something similar to PHP with eval:

Approach No. 1

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

I also saw an approach that calls a Function function :

Approach # 2

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

In MDN , although it sounds like every time an instance is created, performance is revised:

, Function, , . , , .

, :

№ 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);

, , eval, , # 2. , , :

  • , , ?
  • - PHP, ?
+5
1

, . , , window, window, :

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

, , ( Javascript - , , ).

+4

All Articles