Skip to content Skip to sidebar Skip to footer

JavaScript String Of Sub Functions To Actual Functions

I learned I can call functions by a string representing the function name. Example here: http://www.sitepoint.com/call-javascript-function-string-without-using-eval/ My question is

Solution 1:

The thing is Test.SubTest does not exist

SubTest is a property defined in the constructor function Test

That mean that the only way to access this function is to define an object

var t = new Test();
t.SubTest();

The function GetFunction("Test.SubTest") would work if the function was static, like :

function Test() {}
Test.SubTest = function(){}

Solution 2:

var Test = function () {
  this.SubTest = function () {}
} 

var obj = new Test()

obj['SubTest']()

or

Test = function () {}
Test.SubTest = function () {}

window['Test']['SubTest']()

Solution 3:

The problem is because typeof window['Test.SubTest'] is undefined... so, you need to instantiate the super object to call it's sub function(encapsulated function indeed). See bellow code

  .....
      else if ( functions.length > 1 ) {
    var functionObj = window[functions[0]];
    for ( var i = 1; i < functions.length; i++ ) {
      functionObj = eval('new '+functionObj+'().'+functions[i]);
    }
    if ( typeof functionObj === 'function' )
        return functionObj;
    return false;
    }
  .....

EDITS: I your comment stated you don't want to use eval consider the following solution

  .....
      else if ( functions.length > 1 ) {
    var functionObj = window[functions[0]];
    for ( var i = 1; i < functions.length; i++ ) {
       functionObj =new functionObj()[functions[i]];
    }
    if ( typeof functionObj === 'function' )
        return functionObj;
    return false;
    }
  .....

And here is the complete code for test

     function Test() {
       this.SubTest = function() { 
        this.subsubtest=function(){ alert('subsubtest')}
     }
    }

    var functionString = 'Test.SubTest.subsubtest';

    function GetFunction(functionName) {
      var functions = functionName.split('.');
      if ( functions.length === 1 ) {
          var functionObj = window[functions[0]];
          if ( typeof functionObj === 'function' )
              return functionObj;
          return false;
      }
      else if ( functions.length > 1 ) {
          var functionObj = window[functions[0]];
          for ( var i = 1; i < functions.length; i++ ) {
           functionObj =new functionObj()[functions[i]];
          }
          if ( typeof functionObj === 'function' )
              return functionObj;
          return false;
      }
      return false;
  }

  var functionName = 'Test.SubTest.subsubtest';  
  var functionObj = GetFunction(functionName); 
  alert(typeof functionObj);//function

Post a Comment for "JavaScript String Of Sub Functions To Actual Functions"