JavaScript create_function
Creates an anonymous function, and returns its name (funny, eh?)
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 | function create_function (args, code) { // Creates an anonymous function, and returns its name (funny, eh?) // // version: 909.322 // discuss at: http://phpjs.org/functions/create_function // + original by: Johnny Mast (http://www.phpvrouwen.nl) // + reimplemented by: Brett Zamir (http://brett-zamir.me) // * example 1: f = create_function('a, b', "return (a + b);"); // * example 1: f(1, 2); // * returns 1: 3 try { return Function.apply(null, args.split(',').concat(code)); } catch (e) { return false; } } |
Examples
Running
1 2 | f = create_function('a, b', "return (a + b);"); f(1, 2); |
Should return
1 | 3 |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have create_function goodness in JavaScript.
The doc states that this function "Returns a unique function name as a string," like the php version would, the example code looks like it's returning the actual function, not the name of the function (in PHP, it would have named the function something like 'lambda1' and returned it).
If your other functions like array_map() expect a function instead of the function's name, it should be okay - but the documentation would still be wrong.
Also, the example is incorrect or, not clear and I'm not understanding it.


Kevin van Zonneveld
8 Sep '08
You can still handle the functions in the same way as PHP:
Only now both methods pass actual functions instead of function names (what PHP does).
It was a trade-off, because otherwise we would have to work with global variables which would be nasty.
Documentation is currently copied 1-on-1 from the PHP site, to be 100% correct we would have to make exceptions in the documentation, but unfortunately that not our number one priority at the moment.
Thanks for your input.