I need, from within a function, to get it's name (actually I'm going up the stack a bit with .caller but that shouldn't change the problem).
'arguments.callee.name' would solve my problem IF my function had been named. But my functions are declared with var myFunc = function() {}, and changing that is not a possibility (I'm using CoffeeScript which always compiles to var declarations).
So how could I get to the variable to which the function was assigned?
This is for debugging purposes so I'm not worried about performance, I'll use whatever operations get me to the name no matter the processing/time cost.
EDIT: For the record, this is what I implemented in CoffeeScript based on the chosen answer's recommended library:
window.log = (msg) ->
caller = printStackTrace()[4]
caller = caller.substring 0, caller.indexOf('(') - 1
if typeof msg is 'object'
console.log "v --- at #{ caller }: ---"
console.log msg
else console.log "> --- at #{ caller }: " + msg
Works like a charm, thanks everyone!
You might be interested in this javascript stacktrace project on github. In particular, note the findFunctionName method in stacktrace.js.
Basically they re-fetch the javascript source using XMLHTTPRequest and pull the line where the function was declared.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With