0

In my app.js I have defined functions like this:

var func1 = function(v1,v2,v3) {
  .
  .
}

var func2 = function(v1,v2,v3) {
  .
  .
}

In my controller.js:

var action = "";

if(..) { action = 'func1';}
else {action = 'func2'}

action(a1,a2,a3);

However, I get an error, saying that action is not a function. How can I access func1 and func2`` like this?

1
  • 3
    try action=func1 ... action=func2 Commented Apr 25, 2013 at 5:15

2 Answers 2

4

try removing quotes, like, change:

if(..) { action = 'func1';}
else {action = 'func2'}

to

if(..) { action = func1;}
else {action = func2;}

Added: you are assigning string to your action variable when you add quotes for the func1, you can check it doing:

var func1 = function(v1,v2,v3) {
  alert("first");
};
var test_this = func1;
console.log( typeof test_this); //gives you function

where as

var test_this = 'func1'; //with quotes added
console.log( typeof test_this); //gives you string
Sign up to request clarification or add additional context in comments.

9 Comments

Works ..thank you.. can you explain why it is like this? In normal javascript we actually use ''.
unless func1 and func2 are global, action cannot access the function by name anyways. It's rare to identify a function by name in javascript - it would have to be accessed as window[name] (in a browser) or global[name] (everywhere else)
An alternative would be to store the functions in an array or hash. Then you can identify them by their index into this array.
@BhumiSinghal if you are in a non-browser environment like Node.js, window is not the global object.
@BhumiSinghal if you want to encode polymorphic behavior into JSON, you'd encode the function as an index to some look-up table. {"action":"add", "args":[1,2]}
|
1

You're trying to access the function from a string. I'm no expert but you could just try

if (..) {
    func1(a1, a2, a3);
} else {
    func2(a1, a2, a3);
}

1 Comment

actually this is something that is like the basics of programming but i cant do it . I need to access using a var. Thanks

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.