I’m trying to write a helper method in JavaScript. It should act differently if one sends in a function or an reference to a function.
I want to like to use it like this:
helper('div', function () { return false; })
helper('div', obj.fn)
What I can’t figure out is: how to inside the helper function tell the difference between the two?
I think it’s due to that JavaScript first evaluates the obj.fn before it sends it in.
The only workaround I found is to send the obj.fn as an obj, i.e.
helper('div', { fn: obj.fn })
Then I can tell the difference between the two with typeof. But I really like some way to make it without the extra object declaration.
You can use
toString()to find out if the function is anonymous assuming it is declared as a named function and not an unnamed function assigned to a variable:Will give you the name of the function if any.
My previous edit referred to an IE quirk that didn’t exist in other browsers and is no longer valid in IE as of version 9. However, you can still assign named functions as object properties using a named function expression:
This works in all browsers, but IE 8 and lower don’t adhere to the specification which says the function is only available by this name inside its own block.