Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

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

Why this code doesn't work

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

callback(4, console.log("Hello"));

I know I have to do like this:

callback(4, function() { console.log("hello"); });

But I still don't understand the reason why I have to do like that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Lets step through it to help you visualise what is going on. When the interpreter reads your code, it evaluates function expressions inside-out. That is to say:

callback(4, console.log("Hello"));
//          ^------------------^---- is evaluated before "callback" is called.

A longer-form way of writing this which produces the same outcome would be:

var result = console.log("Hello");
callback(4, result);

The console.log function doesn't have a defined return value (or at least not a standardised one) - though incidentally all functions in javascript return something - when unspecified this value is literally undefined. So when you run your code you are essentially calling:

callback(4, undefined);

This means that inside callback, trying to call func as a function will result in:

TypeError: undefined is not a function

This is why you need to encapsulate your logic in a new function-closure - whereby func obtains a reference to a callable Function object.


So How Can I Tidy Up My Code?

Generally in simple cases like this, what you have done to solve the problem is perfectly acceptable but with more complex logic, you can often end up with several levels of nested callbacks (sometimes referred to as "callback-soup"). To improve readability where code reuse is common you can introduce a function-factory which hides away the nastiness, for example:

function myLogger(message){
    return function(){
        console.log(message);
    }      
}

callback(4, myLogger('hello'));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...