Javascript eval () for function with argument

How to do it?

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

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

function isInFavorites(url) { return true; } // returns boolean
+5
source share
3 answers

Do not use eval()first of all.

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

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

Functions are objects, and you can assign a function reference to any variable. Then you can use this link to call the function.

+6
source

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

if ( window[iCheckFcn](itemSrc) ) {
  alert("it a favorite");
};
+2
source

AngularJS, :

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

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

All Articles