我想知道JavaScript是否支持在另一个函数内编写函数,或者嵌套函数(我在一篇博客中读到过)。这真的可能吗?实际上,我已经使用过这些,但对这个概念不确定。我对此非常不清楚--请帮帮我!
这真的可能吗。
是的。
function a(x) { // <-- function
function b(y) { // <-- inner function
return x + y; // <-- use variables from outer scope
}
return b; // <-- you can even return a function.
}
console.log(a(3)(4));
var foo = function () { alert('default function'); }
function pickAFunction(a_or_b) {
var funcs = {
a: function () {
alert('a');
},
b: function () {
alert('b');
}
};
foo = funcs[a_or_b];
}
foo();
pickAFunction('a');
foo();
pickAFunction('b');
foo();
函数是一等对象,可以:
以Kenny给出的示例为基础:
function a(x) {
var w = function b(y) {
return x + y;
}
return w;
};
var returnedFunction = a(3);
alert(returnedFunction(2));
会用警报以5的数字提醒您。
是的,可以编写并调用嵌套在另一个函数中的函数。
尝试这样做:
function A(){
B(); //call should be B();
function B(){
}
}
不仅可以将作为变量传入另一个函数的函数返回,还可以在函数外定义它并在内部进行计算。请看以下示例:
function calculate(a,b,fn) {
var c = a * 3 + b + fn(a,b);
return c;
}
function sum(a,b) {
return a+b;
}
function product(a,b) {
return a*b;
}
document.write(calculate (10,20,sum)); //80
document.write(calculate (10,20,product)); //250
使用ES6的另一种解决方案:
const currying = (x) => (y) => x + y;
console.log(currying(5)(3));
将会在控制台中打印:8
function calculate(num1) {
// arrow function
return (num2) => num1 + num2;
}
// Invoke the function
console.log(calculate(4)(6));
function add(x, y) {
// we can define another function inside the add function to print our answer
function print(ans) {
console.log(ans)
}
const ans = x + y
print(ans)
return ans
}
add(1, 2)