Invoke a JavaScript function with parameter in a function -


today, saw following code below:

log_execution_time = require('./utils').log_execution_time; var fib = function fib(n) {     if (n < 2) return n;     return fib(n - 1) + fib(n - 2); };  var timed_fib = log_execution_time(fib); timed_fib(5);  >>> execution time: 1.166ms 

i curious function log_execution_time. don't know how is.

you can see input of log_execution_time function. how can call function parameter? of methods w3school need parameter when calling function. assume:

var log_execution_time = function (input_function){ console.time("execution time"); // input_function console.timeend("execution time"); } 

thanks , regards

i think op how 5 parameter gets passed function input_function

functions first class objects in javascript. can set identifiers , pass references around same other object.

  1. log_execution_time(fib); not invoke fib, passes reference fib log_execution_time function first argument. means internals can reference fib
  2. timed_fib function can reference closure invocation of log_execution_time due when created, can hence invoke reference fib desired

here simple example;

function log(msg) {     console.log(msg); }  function wrap(fn) {     return function () { // anonymous function our wrapper         console.log('wrapped:');         fn.apply(this, arguments); // line invokes `fn` whatever arguments                                     // passed anonymous function     }; }  var foo = wrap(log); foo('hello world'); // logs // wrapped: // hello world 

we have used more usual way invoke fn, example fn("fizz buzz");, instead of .apply mean needed know more how invoke fn, have been anything


useful stuff:


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -