Node JS How to Convert String into Object

The exampleCode is:

// 4. execute tower.init latter read from bellow (1)
tower={
  init:function(){ console.log('horee im here now, finaly after a day code');}
}

// 3. app object
app ={ 
  publish:function(what,data){
     data.nextModule.init();
  }
}
// 2. then call this funct
var fires = function(){
   return app.publish('subscriber',{ nextModule : 'tower'});
}
// 1. execute this first
fires();

Explanation Problem

  • When i fire fires() 1.
  • The 2. isfine app.publish('text',{nextModule:'tower');
  • Bypassed to 3. app.publish(text,data)

My problem is

I want to convert data.nextmodule --> into an Object or Function then call the tower module.init()

data.nextModule.init() cannot executed because nextModule is String

how to make this code run like this

data.'tower'.init();

I have reading this reference

Answer by Houshalter converting an object to a string !not an String into an Object

Can node js to that?
Can we covert to object as easy as JSON.stringify(data) ?

UPDATE ERROR on terminal

         throw err;
            ^
 TypeError: Object tower has no method `init`

Two things, first change the identifier new to something else.

Second,

data.newxtModule is a string that represents variable in your script. All variables are part of the GLOBAL object. So you can just retrieve that variable by passing that variable's name in string format to the GLOBAL object. And you will be able to call the init() of tower.

Simply change this line,

data.nextModule.init();

To,

GLOBAL[data.nextModule].init();

Final code should look like this.

// 4. execute tower.init latter read from bellow (1)
tower={
  init:function(){ console.log('horee im here now, finaly after a day code');}
}

// 3. app object
app ={ 
  publish:function(what,data){
     GLOBAL[data.nextModule].init();
  }
}
// 2. then call this funct
var new1 = function(){
   return app.publish('subscriber',{ nextModule : 'tower'});
}
// 1. execute this first
new1();

Here is Fiddle

Change 'tower' to tower.

By the way, you'd better do not use the key word 'new'.