phpjs
Version:
72 lines (59 loc) • 2.46 kB
Markdown
layout: page
title: "JavaScript call_user_func function"
comments: true
sharing: true
footer: true
alias:
- /functions/view/call_user_func:363
- /functions/view/call_user_func
- /functions/view/363
- /functions/call_user_func:363
- /functions/363
<!-- Generated by Rakefile:build -->
A JavaScript equivalent of PHP's call_user_func
{% codeblock funchand/call_user_func.js lang:js https://raw.github.com/kvz/phpjs/master/functions/funchand/call_user_func.js raw on github %}
function call_user_func (cb) {
// From: http://phpjs.org/functions
// + original by: Brett Zamir (http://brett-zamir.me)
// + improved by: Diplom@t (http://difane.com/)
// + improved by: Brett Zamir (http://brett-zamir.me)
// * example 1: call_user_func('isNaN', 'a');
// * returns 1: true
var func;
if (typeof cb === 'string') {
func = (typeof this[cb] === 'function') ? this[cb] : func = (new Function(null, 'return ' + cb))();
}
else if (Object.prototype.toString.call(cb) === '[object Array]') {
func = (typeof cb[0] === 'string') ? eval(cb[0] + "['" + cb[1] + "']") : func = cb[0][cb[1]];
}
else if (typeof cb === 'function') {
func = cb;
}
if (typeof func !== 'function') {
throw new Error(func + ' is not a valid function');
}
var parameters = Array.prototype.slice.call(arguments, 1);
return (typeof cb[0] === 'string') ? func.apply(eval(cb[0]), parameters) : (typeof cb[0] !== 'object') ? func.apply(null, parameters) : func.apply(cb[0], parameters);
}
{% endcodeblock %}
- [Raw function on GitHub](https://github.com/kvz/phpjs/blob/master/functions/funchand/call_user_func.js)
Please note that php.js uses JavaScript objects as substitutes for PHP arrays, they are
the closest match to this hashtable-like data structure.
Please also note that php.js offers community built functions and goes by the
[McDonald's Theory](https://medium.com/what-i-learned-building/9216e1c9da7d). We'll put online
functions that are far from perfect, in the hopes to spark better contributions.
Do you have one? Then please just:
- [Edit on GitHub](https://github.com/kvz/phpjs/edit/master/functions/funchand/call_user_func.js)
### Example 1
This code
{% codeblock lang:js example %}
call_user_func('isNaN', 'a');
{% endcodeblock %}
Should return
{% codeblock lang:js returns %}
true
{% endcodeblock %}
### Other PHP functions in the funchand extension
{% render_partial _includes/custom/funchand.html %}