Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript eval() for function with argument

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
like image 480
FFish Avatar asked Oct 14 '10 17:10

FFish


2 Answers

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.

like image 162
Pointy Avatar answered Oct 19 '22 03:10

Pointy


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

if ( window[iCheckFcn](itemSrc) ) {
  alert("it's a favorite");
};
like image 21
Ashley Williams Avatar answered Oct 19 '22 03:10

Ashley Williams