Creating a dynamic object

I have a function that takes the name of a string object, and I need a function to create a new instance of the object with the same name as the string value

For instance,

function Foo(){}
function create(name){
    return new name();
}
create('Foo'); //should be equivalent to new Foo();

As long as I know that this is possible through eval, it would be nice to try to avoid using it. I am also wondering if anyone has any alternative ideas for the problem (below)


I have a database and a set (using the classic OO methodology), roughly one for each table, that defines the common operations in this table. (Very similar to Zend_Db for those using PHP). Since everything asynchronously performs tasks based on the result of the latter, it can lead to very aligned code

var table1 = new Table1Db();
table1.doFoo({
    success:function(){
        var table2 = new Table2Db();
        table2.doBar({
            notFound:function(){
                doStuff();
            }
        });
    }
});

, .

Db.using(db) //the database object
  .require('Table1', 'doFoo', 'success') //table name, function, excpected callback
  .require('Table2', 'doBar', 'notFound')
  .then(doStuff);

. , , , require, ...

+3
2

require? , . :

Db.using(db) //the database object
  .require(Table1Db, 'doFoo', 'success') //table constructor, function name, expected callback
  .require(Table2Db, 'doBar', 'notFound')
  .then(doStuff);

, ...

, eval? , ( ). , .

, eval, (.. ), :

function create(name) {
  return new window[name]();
}

(.. create('MyCompany.MyLibrary.MyObject'), - :

function create(name) {
  var current,
      parts,
      constructorName;

  parts = name.split('.');
  constructorName = parts[parts.length - 1];
  current = window;
  for (var i = 0; i < parts.length - 1; i++) {
    current = current[parts[i]];
  }

  return new current[constructorName]();
}
+4

. Annabelle , , ( ), . ( )

function Foo(){}
function create(name){
    return new name();
}
create(Foo); // IS equivalent to new Foo();

, :) . .

,

new 'Foo'()

, ? , return new name(); return new Foo(); , .

, . !

: - , , , .

+2

Source: https://habr.com/ru/post/1753958/


All Articles