Tuesday, 28 February 2012

Creating a function with a true name defined at runtime

I used to have an article here showing how to dynamically create functions with true names. Except it didn't work properly on Firefox and there's a much better way (which does work properly on Firefox) described in this article by Marcos Cáceres. It looks like this:

var name = "foo"; 
var func = new Function(
     "return function " + name + "(){ alert('sweet!')}"

Yes, the Function constructor is basically a call to eval, so you'd only do this with input you control well. But when you need to do it, this is how.

Nice one, Marcos!

No comments: