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
  • 35,848
  • 27
  • 79
  • 88
basagabi
  • 4,598
  • 6
  • 33
  • 78

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
  • 155,085
  • 27
  • 166
  • 222
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>
Juan Mendes
  • 85,853
  • 29
  • 146
  • 204
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,503
  • 11
  • 15