1

How do I check if the return variable is a function?

var testController = function() {
  alert('123');
}

$(function() {
  $('[mfour]').each(function(e, t) {
    var a = $(t).attr('mfour');
    console.log($.isFunction(testController));
    console.log($.isFunction(a));
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div mfour="testController">asd</div>

Notice that on first console.log returns TRUE when the function name is hard-coded while on the second console.log if the variable is being evaluated returns FALSE.

It is kind of weird because var a returns testController.

Here's the jsFiddle.

My goal here is to run certain functions base on the mfour attribute. So in the example above, testController will run testController function.

Paul Roub
  • 36,322
  • 27
  • 84
  • 93
basagabi
  • 4,900
  • 6
  • 38
  • 84

3 Answers3

2

Try using window[varname] - assuming the function is in global scope

like this

DEMO

var testController = function() {
    alert('123');
}

$(function() {
    $('[mfour]').each(function(e, t) {
        var a = $(t).attr('mfour');
        console.log($.isFunction(testController));
        console.log($.isFunction(window[a]));
        console.log(typeof window[a] === "function");
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div mfour="testController">Hello</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
2

In your example, to get a reference to the testFunction if it is in scope, you can use eval. Yes, I said it, eval, so you have to know that the string could be manipulated by the user to run malicious code if you don't sanitize it for function names;

var testController = function() {
  alert('123');
}

$(function() {
  $('[mfour]').each(function(e, t) {
    var a = eval($(t).attr('mfour'));
    console.log($.isFunction(testController));
    console.log($.isFunction(a));
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div mfour="testController">Hello</div>
Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
1

To check if the variable is a function just add a check

typeof variableName

It will return the type of variable.

Dude..

If possible, add your function to an object. Like below

var obj = {
    testController: function(){
       alert('123');
    }
};

    $(function() {
        $('[mfour]').each(function(e, t) {
            var a = $(t).attr('mfour');
            console.log($.isFunction(obj[a]));
        })
    });
Swaprks
  • 1,553
  • 11
  • 16