Why I can't directly set console.log() as callback function

后端 未结 4 1510
遇见更好的自我
遇见更好的自我 2020-12-21 05:47

Why this code doesn\'t work

function callback(num, func) {
    for(var i = 0; i < num; i++) {
        func();
    }
}

callback(4, console.log(\"Hello         


        
4条回答
  •  情深已故
    2020-12-21 06:33

    Because functions are first-class citiziens in Javascript (meaning functions can be stored in variables). passing a function as an argument will return a reference to the function definition rather than the function call you're trying to invoke. It does however evaluate your console.log beforehand and passes it on as a variable and since your log's function call doesn't return anything it passes undefined to your callback function.

    function test( logFunction ){
        logFunction( 'test' )
    }
    
    test( alert )
    

    Is an example of this behaviour. It's also the reason closures like the one demonstrated by Remy J work.

    function callback(num, func) {
        for(var i = 0; i < num; i++) {
            func( "Hello" );
        }
    }
    
    callback(4, alert);
    

    This would work.

提交回复
热议问题