0

I currently store a function in a variable, and then call it:

var function_name = 'test_function';


// some other JS here    


if (typeof app[function_name] != 'undefined') {
     app[function_name];
}


app.test_function = function() {
    alert('woo');
};

This works fine, but what if I store arguments in the function name variable? Like this:

var function_name = 'test_function("mike")';


// some other JS here    


if (typeof app[function_name] != 'undefined') {
     app[function_name];
}


app.test_function = function(name) {
    alert(name);
};

This doesn't work, because typeof app[function_name] is undefined. How can I do this?

3
  • whats the use of statement app[function_name];? Commented Jun 16, 2016 at 11:52
  • what does you app has? Commented Jun 16, 2016 at 12:00
  • Why not pack the arguments separately from the function definition? You could then use the same logic to lookup the function and delegate calling the function with the supplied arguments, much like lodash.curry Commented Jun 16, 2016 at 12:23

2 Answers 2

1

'test_function("mike")' is not a valid function name.

Your logic needs to change to

var function_name = 'test_function("mike")';
var app = {};
app.test_function = function(name) 
{
  console.log(name)
};
var split = function_name.split(/[()]/);
var funName = split[0];
var arguments = [];
if (funName != function_name) 
{
  var arguments = split[1].split(",");
}
if (typeof app[funName] != 'undefined') 
{
  app[funName].apply(null, arguments);
}

Sign up to request clarification or add additional context in comments.

Comments

1

function name should/will not change but the definition will!

var function_name = 'test_function';
var app = {};
if (typeof app[function_name] != 'undefined') {
  app[function_name];
}
app.test_function = function(name) {
  alert(name);
};
app.test_function('Hey');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.