Tuesday 7 January 2020

javascript - Check if a variable is of function type



Suppose I have any variable, which is defined as follows:




var a = function() {/* Statements */};


I want a function which checks if the type of the variable is function-like. i.e. :



function foo(v) {if (v is function type?) {/* do something */}};
foo(a);


How can I check if the variable a is of type Function in the way defined above?



Answer



Sure underscore's way is more efficient, but the best way to check, when efficiency isn't an issue, is written on underscore's page linked by @Paul Rosania.



Inspired by underscore, the final isFunction function is as follows:



function isFunction(functionToCheck) {
return functionToCheck && {}.toString.call(functionToCheck) === '[object Function]';
}

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...