Dynamically Instantiate a Function & Call a Method in JavaScript -


take javascript class:

var foo = function() {      this.bar = function() {         return 'foobar';     };  }; 

i can instantiate class , call it's bar method this:

(new foo).bar(); 

i achieve instantiation , calling of class , it's method dynamically based of string represents class , method foo@bar.

i have tries following achieve receive error uncaught typeerror: string not function:

var action = 'foo@bar'; var classmethod = action.split('@');  (new classmethod[0]).call(classmethod[1]); 

is possible in javascript or going in wrong way?

you eval. won't show because eval evil.

if willing create object containing types can created:

var foo = function() {     this.bar = function() {         return 'foobar';     }; };   var types = {     foo : foo };  var action = 'foo@bar'; var classmethod = action.split('@');  (new types[classmethod[0]])[classmethod[1]](); 

the problem code classmethod[0] string. use new need give function. in code make use of javascript's [] operators accesses properties of object using string containing property's name. first use foo property types object. constructor. after calling constructor, use [] operators again bar property.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -