javascript - Why I can't directly set console.log() as callback function -
why code doesn't work
function callback(num, func) { for(var = 0; < num; i++) { func(); } } callback(4, console.log("hello"));
i know have this:
callback(4, function() { console.log("hello"); });
but still don't understand reason why have that.
lets step through visualise going on. when interpreter reads code, evaluates function expressions inside-out. say:
callback(4, console.log("hello")); // ^------------------^---- evaluated before "callback" called.
a longer-form way of writing produces same outcome be:
var result = console.log("hello"); callback(4, result);
the console.log
function doesn't have defined return value (or @ least not standardised one) - though incidentally functions in javascript return something - when unspecified value literally undefined
. when run code calling:
callback(4, undefined);
this means inside callback
, trying call func
function result in:
typeerror: undefined not function
this why need encapsulate logic in new function-closure - whereby func
obtains reference callable function
object.
so how can tidy code?
generally in simple cases this, have done solve problem acceptable more complex logic, can end several levels of nested callbacks (sometimes referred "callback-soup"). improve readability code reuse common can introduce function-factory hides away nastiness, example:
function mylogger(message){ return function(){ console.log(message); } } callback(4, mylogger('hello'));
Comments
Post a Comment