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
5parameter gets passed functioninput_function
functions first class objects in javascript. can set identifiers , pass references around same other object.
log_execution_time(fib);not invokefib, passes reference fiblog_execution_timefunction first argument. means internals can referencefibtimed_fibfunction can reference closure invocation oflog_execution_timedue when created, can hence invoke referencefibdesired
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
Post a Comment