请参阅此示例:
var tools1 = require('../tools/tools1');
var test_func = function(arg1, arg2, arg3) {
var local_var_1 = "lc1";
var local_var_2 = "lc2";
return function(data) {
var result = tools1.doSth(local_var_1);
result = result+local_var_2;
}
}
exports.test_func = test_func;
我不明白内部函数的用途是什么!
最佳答案
在 javascript 中,当您返回函数时,它会返回该函数的引用,您可以稍后调用它。
在代码中,当您执行 var result = test_func()
时,result
将保存该函数的引用。然后您可以调用返回的函数,例如 result(data)
。
一个基本示例:
function sum(x, y) {
var rs = x+y;
return function(message) {
console.log(message + rs); //rs holds its value because of clousers
}
}
var result = sum(2, 3);
result("This is result: ");
Variables that are used locally, but defined in an enclosing scope like
rs
in above example because of Closures
关于javascript - Nodejs 中的 function in function 到底做了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42083929/