为什么我不能直接设置console.log()作为回调函数 [英] Why I can't directly set console.log() as callback function

查看:745
本文介绍了为什么我不能直接设置console.log()作为回调函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码不起作用

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

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

我知道我必须这样做:

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

但我还是不明白我为什么要这样做。

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

推荐答案

让我们一步一步来帮助您直观地了解发生了什么。当解释器读取您的代码时,它会评估内向外的函数表达式。也就是说:

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);

console.log 函数有一个定义的返回值(或至少不是一个标准的) - 虽然附带的JavaScript中的所有函数返回某事 - 当未指定此值的字面上 undefined 。所以当你运行你的代码,你基本上是调用:

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);

这意味着回调调用 func 作为函数将导致:

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


TypeError:undefined不是函数

TypeError: undefined is not a function

这就是为什么你需要将你的逻辑封装在一个新的函数闭包中 - func 获得对可调用 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.

那么我如何整理我的代码?

通常在这种简单的情况下,完全可以接受,但具有更复杂的逻辑,你可能会遇到几个层次的嵌套回调(有时称为callback-soup)。为了提高代码重用常见的可读性,你可以引入一个函数工厂来隐藏空白,例如:

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'));

这篇关于为什么我不能直接设置console.log()作为回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆