与回调函数中使用函数表达式instated箭头功能
问题描述:
我有下面这段代码工作得很好,当我用箭头功能作为一个回调函数与回调函数中使用函数表达式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未定义。
答
在你的第二个片段中,你没有传递函数,你调用函数,然后将结果作为参数传递。你想
getNumber(10, action); // x is not defined
function action(x){
console.log(x);
}
答
尝试运行下面的代码
var getNumber = function (argument, callback) {
callback(argument - 1);
}
getNumber(10, action); // x is not defined
function action(x){
console.log(x);
}
你打电话的动作(X),而其预期的功能,有你在哪里打电话没有x的值动作(x)因此它提出了错误
答
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
因为你不是passi一个函数表达式,即你调用一个名为'action'的函数 –