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

后端 未结 4 1517
遇见更好的自我
遇见更好的自我 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:12

    That's because when you mentioned console.log(), you asked the js engine to evaluate it and it does and passes the result as the 2nd arg to the callback function and not a function object as it expects and hence the call doesn't behave as u desire. The working case correctly passes a function object when u pass a function(){} construct.

提交回复
热议问题