简体   繁体   中英

JavaScript (NodeJS) equivalent for PHP's call_user_func_array()

Is there any equivalent function in JavaScript (NodeJS) similar to PHP's call_user_func_array ( http://php.net/manual/en/function.call-user-func-array.php ). Which allows to call a function with array of parameters.

In my case, I have to call util.format with parameters that will be in an array.

Here is very simple example trying to show it.

var util = require("util");

function my_fundtion(items) {
  var format_string = "";
  for (var i=0; i < items.length; i++) {
    format_string += " %s";
  }
  return util.format(format_string, /* here I want to pass items in items array */);
}

PHP has:

call_user_func_array('myfunc', array(1, 2, "foo", false));

While JS has:

myfunc.apply(null, [1, 2, "foo", false]);

The first null goes in the position of an object. You will make use of that if the function is intended to be a method. An example on using such invocation would be to slice array-like objects which are not arrays at all but seem like one (like the arguments object inside of a function):

Array.prototype.slice.apply(arguments, []);

Generally speaking, the syntax is:

(afunction).apply(obj|null, array of arguments)

You can try this:

function my_fundtion(items) {
    var format_string = "";
    for (var i=0; i < items.length; i++) {
        format_string += " %s";
    }
    var new_items = items.slice();
    new_items.unshift(format_string);
    return util.format.apply(null, new_items);
}

IMHO that's the wrong approach for a function. Have you tried the following?

function my_fundtion(items) {
    return items.join(" ");
}

Because call_user_func_array call function referenced by the function name which is in string. So, in JS we need to use eval .

Example:

const popup = (msg) => {
 alert(msg);
}

const subject = {
 popup(msg) {
  alert(msg);
 }
}

So,

eval("popup").apply(null, ['hi'])
eval("subject.popup").apply(null, ['hi'])

Correct me. If i wrong. ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM