首页 文章

匿名函数作为参数

提问于
浏览
-1
function cbTest(name,function(){
    console.log("Hello ",name);
})


cbTest("john");

我收到以下错误 .

(function(exports,require,module,__ filename,__ dirname){
function cbTest(name,function(){
^^^^^^^^
SyntaxError:在Module._compile(module.js:413:25)的exports.MunInThisContext(vm.js:53:16)处的Object.Module._extensions..js(module.js:452:10)处的意外的令牌函数at at在启动时在Function.Module.runMain(module.js:475:10)的Function.Module._load(module.js:310:12)上的Module.load(module.js:355:32)(node.js:117) :18)在node.js:951:3

这段代码出了什么问题?

更新:我试图让匿名函数作为参数工作,但无论如何,下面应该是这样的 .

function getName(name){
    return name;
}

function cbTest(name,cb){
    console.log("hello ",cb(name));
}

cbTest("John",getName);

2 回答

  • 4

    当您声明一个函数时,参数列表只能包含参数的名称(以及ES2015中的扩展运算符 ... ) . 你're trying to declare a function with an instantiated function in the parameter list, which just doesn' t有意义 .

    当你是 calling 函数时,匿名函数在参数列表中是有意义的,但是当它是 declaring 时则不行 .

  • 0

    这段代码没有任何意义

    它可以是:

    function cbTest(name) {
        console.log("Hello ",name);
    }
    
    cbTest("john");
    

    要么

    function cbTest(name, func) {
        func(name);
    }
    
    
    cbTest("john", function(name){
        console.log("Hello ",name);
    });
    

    你不能在函数声明中传递任何东西

相关问题