Call all Javascript functions in a list

What is the most idiomatic way to call all functions in a list?

The best I can think of:

myFunctions.forEach(function(f){f();});

Is there a more idiomatic way to do this?

EDIT:

At the moment, I'm only interested in ES5. Perhaps there is some way to do with Array prototypes?

+4
source share
8 answers

What about ES6? You can use the arrow function .

This will:

myFunctions.forEach( f => f());

You can already use it today with a tool like babel . For an overview of ES6 features, run es6features .

EDIT:

You can expand the object Arrayas follows:

Array.prototype.invokeFunctions = function () {
    this.forEach(function (f) {
    if (typeof(f) === "function")
      f()
    });
}

var functions = [
    function () { console.log(1);},
    function () { console.log(2);}
];

functions.invokeFunctions();
// output 
1
2

, , Array. , . :

function FunctionList(functions) {
  this.functions = functions;
}

FunctionList.prototype.callAll = function () {
  this.functions.forEach(function (f) {
    if (typeof(f) === "function")
      f()
  });
}

var functionList = new FunctionList(functions);
functionList.callAll();

, . , , FunctionList. , getter setter, / .

+3

, :

myFunctions.map(Function.prototype.call, Function.prototype.call);

, :

var call = Function.prototype.call;
myFunctions.map(call, call);

:

[].map.apply(fns, [call, call]);
+2

, , es6 ;)

funcs.forEach(x => x());

es6, Babel.

+1

forEach. ES6, , -, - :

var callSelf = function(funcToCall) {
    funcToCall();
}

:

myFunctions.forEach(callSelf);
+1
function callEach(scope, funcs) {
  funcs.forEach(function (f) { f.call(scope); });
}

callEach(this, myFunctions);

, .

0

, . :

var results = fns.map(function(fn){return fn();});
0

in-in , ( ).

var ts = [function (){alert('a');}, function (){alert('b');}];
for (var tsIndex in ts) ts[tsIndex]();
Hide result

a b.

: .

0

, , .

function c() {
    console.log("c");
}

function b() {
    console.log("b");
    return c;
}

function a() {
    console.log("a");
    return b;
}

for(var f = a; f instanceof Function; f = f());
0

Source: https://habr.com/ru/post/1589277/


All Articles