7

How do I do this?

function myUIEvent() {
    var iCheckFcn = "isInFavorites";
    var itemSrc = ui.item.find("img").attr("src");

    if (eval(iCheckFcn(itemSrc))) { alert("it's a favorite"); }

function isInFavorites(url) { return true; } // returns boolean
1
  • 2
    You might want to start by writing syntactically valid code. You're missing a closing brace somewhere in there. Commented Oct 14, 2010 at 17:44

3 Answers 3

8

Don't use eval(), first of all.

function myUIEvent() {
  var iCheckFcn = isInFavorites;
  var itemSrc = ui.item.find("img").attr("src");

  if (iCheckFcn(itemSrc)) { alert("it's a favorite"); }
}

Functions are objects, and you can assign a reference to a function to any variable. You can then use that reference to invoke the function.

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

2 Comments

I think that missed the point of the question. Your example still hardcodes the var iCheckFcn to the hardcoded value isInFaorites. The question specifically asked how to do set the iCheckFcn dynamically with the name of the function NOT hardcoded but passed in as a variable ( in his example called var iCheckFcn is assigned in this case a hardcoded string but could be a dynamically passed in string.
@PaulGorbas you realize that this is over 6 years old, right? Anyway, references to functions can be passed as parameters, and there's still no need for eval().
2

The best way is what Pointy described, or alternatively you could just do this:

if ( window[iCheckFcn](itemSrc) ) {
  alert("it's a favorite");
};

Comments

-2

If you are in AngularJS environment, its just that simple:

$rootScope.calculate = function(param1,param2)
{
    console.log(param1+param2);
}

var func = '$rootScope.calculate';
eval(func)(1,2);  //---> 3

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.