(), ,
function log(arg) { console.log(arg); }
setTimeout(log, 1000)
log("hi");
,
function logUsingTheLogMethod( callback ) {
if ( typeof callback === "function" ) {
callback( "This will log to the console!" );
callback( log === callback );
}
}
logUsingTheLogMethod( log );
JS,
Say that you have some functions that did the math, but you don't want to write a logging method for all of them.
function add(a,b,fn) {
if ( fn === log ) {
fn( a + b );
}
}
function subtract(a,b,fn) {
if ( fn === log ) {
fn( a - b );
}
}
add(1, 2, log);
subtract(5, 4, log)
or change a function to provide a function instead of a log function, and you can do anything with the answer
function add(a,b,fn) {
if ( typeof fn === "function" ) {
fn( a + b );
}
}
add( a, b, function ( answer ) {
alert( answer );
});
Trevor source
share