2017-08-31 28 views
0

我有下面这段代码工作得很好,当我用箭头功能作为一个回调函数与回调函数中使用函数表达式instated箭头功能

var getNumber = function (argument, callback) { 
callback(argument - 1); 
} 
getNumber(10, (x)=>{ 
console.log(x); // x = 9 
}); 

现在,当我想改变箭头的功能函数表达式下面的代码。

var getNumber = function (argument, callback) { 
callback(argument - 1); 
} 
getNumber(10, action(x)); // x is not defined 
function action(x){ 
console.log(x); 
} 

可悲的是我得到错误说x未定义。

+5

因为你不是passi一个函数表达式,即你调用一个名为'action'的函数 –

回答

5

在你的第二个片段中,你没有传递函数,你调用函数,然后将结果作为参数传递。你想

getNumber(10, action); // x is not defined 
function action(x){ 
    console.log(x); 
} 
1

尝试运行下面的代码

var getNumber = function (argument, callback) { 
 
callback(argument - 1); 
 
} 
 
getNumber(10, action); // x is not defined 
 
function action(x){ 
 
console.log(x); 
 
}

你打电话的动作(X),而其预期的功能,有你在哪里打电话没有x的值动作(x)因此它提出了错误

1
var getNumber = function (argument, callback) { 
callback(argument - 1); 
} 

function action(x){ 
console.log(x); 
} 

getNumber(10, action); // pass callback function, not result of the call