无法理解 Javascript 高阶函数中的基本概念
Trouble understanding a basic concept in Javascript Higher Order Functions
我在理解 javascript 中的高阶函数时遇到了一些麻烦。
有人可以向我解释这两种情况下发生的事情的区别吗?
场景 1:
// A function that takes in a number (x) and adds one to it.
function doMath(x){
return function (x){
return x + 1;
}
}
var didMath = doMath(5);
console.log(didMath()); // returns error
var didMath = doMath();
console.log(didMath(5)); // returns 6
var didMath = doMath(100);
console.log(didMath(5)); // still returns 6
场景 2:
function doMath2(x,callback){
return callback(x);
}
function add(x){
return x + 1;
}
console.log(doMath2(5,add)); // returns 6, works perfectly fine
我的印象是闭包可以访问其包含函数的参数。为什么在场景 1 中,doMath 中的 "x" 参数不能被包含的函数访问?
在场景 1
第一个输出错误,因为返回的函数需要一个参数,而您没有给出。如果您删除它有效的参数:
// A function that takes in a number (x) and adds one to it.
function doMath(x){
return function (){ // <--- here
return x + 1;
}
}
var didMath = doMath(5);
console.log(didMath());
在你的另外两个例子中,你确实给出了一个论点,这就是一个被考虑在内的论点。不是您作为参数提供给 doMath()
的值
这里发生的事情是你永远不会存储 x 的值,你总是 return 一个新函数,看看这个例子它应该按你预期的那样工作,也许可以帮助你理解
function doMath(x){
var y = x;
return function(y){
return y + 1;
}
}
我在理解 javascript 中的高阶函数时遇到了一些麻烦。
有人可以向我解释这两种情况下发生的事情的区别吗?
场景 1:
// A function that takes in a number (x) and adds one to it.
function doMath(x){
return function (x){
return x + 1;
}
}
var didMath = doMath(5);
console.log(didMath()); // returns error
var didMath = doMath();
console.log(didMath(5)); // returns 6
var didMath = doMath(100);
console.log(didMath(5)); // still returns 6
场景 2:
function doMath2(x,callback){
return callback(x);
}
function add(x){
return x + 1;
}
console.log(doMath2(5,add)); // returns 6, works perfectly fine
我的印象是闭包可以访问其包含函数的参数。为什么在场景 1 中,doMath 中的 "x" 参数不能被包含的函数访问?
在场景 1 第一个输出错误,因为返回的函数需要一个参数,而您没有给出。如果您删除它有效的参数:
// A function that takes in a number (x) and adds one to it.
function doMath(x){
return function (){ // <--- here
return x + 1;
}
}
var didMath = doMath(5);
console.log(didMath());
在你的另外两个例子中,你确实给出了一个论点,这就是一个被考虑在内的论点。不是您作为参数提供给 doMath()
这里发生的事情是你永远不会存储 x 的值,你总是 return 一个新函数,看看这个例子它应该按你预期的那样工作,也许可以帮助你理解
function doMath(x){
var y = x;
return function(y){
return y + 1;
}
}